如何简化这段代码?如何在Laravel集合中添加一个字段?

huangapple go评论65阅读模式
英文:

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.

如何简化这段代码?如何在Laravel集合中添加一个字段?

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);
}

huangapple
  • 本文由 发表于 2023年5月26日 00:18:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76334383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定