products:
id | name | author_id
authors:
id | name
product:
public function author() {
return $this->belongsTo('App\Author');
}
然后我得到了产品:
$products = Product::where('name','like','username%')->get();
foreach ($products as $product) {
$product->author;
}
有没有办法让产品与作者无循环?
答案 0 :(得分:1)
您需要使用eager loading:
$products = Product::where('name','like','username%')->with('author')->get();