得到没有循环查询的相关模型

时间:2015-12-30 12:34:53

标签: laravel laravel-5 eloquent laravel-5.1 eager-loading

表:

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

有没有办法让产品作者无循环?

1 个答案:

答案 0 :(得分:1)

您需要使用eager loading

 $products = Product::where('name','like','username%')->with('author')->get();