英文:
how to simplify this code? how to add a field in laravel collection
问题
foreach (Location::all() as $l) {
$count = Book::where('title', 'LIKE', "%$keyword%")
->where('location_id', '=', $l->id)
->count();
$dataLocation[] = array(
'id' => $l->id,
'code' => $l->code,
'name' => $l->name,
'count' => $count
);
}
$location = collect($dataLocation);
英文:
foreach (Location::all() as $l) {
$count = Book::where('title', 'LIKE', "%$keyword%")
->where('location_id', '=', $l->id)
->count();
$dataLocation[] = array(
'id' => $l->id,
'code' => $l->code,
'name' => $l->name,
'count' => $count
);
}
$location = collect($dataLocation);
how can I add a field in a laravel collection?
The value of this field is obtained from a query or logic if else
.
I expect laravel collection can add a variable and make the code simple
答案1
得分: 1
根据你的预期输出,你应该有一个类似这样的查询:
$locations = Location::withCount(['books' => fn($q) => $q->where('title', 'LIKE', "%$keyword%")])
->select('id', 'code', 'name')
->get();
而且显然你的 Location 模型中应该定义了与 Book 模型的关系,如下所示:
public function books()
{
return $this->hasMany(Book::class);
}
英文:
From your expected output you should have a query like this
$locations = Location::withCount([ 'books' => fn($q) => $q->where('title', 'LIKE', "%$keyword%") ])
->select('id', 'code', 'name')
->get();
and obviously a relationship defined in your Location model for Book model like below.
public function books()
{
return $this->hasMany(Book::class);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论