无需循环查询即可获取相关模型

get related model without loop query

表:

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

有没有什么方法可以在不循环的情况下通过 author 获得 products

您需要为此使用 eager loading

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