Ad

Get Related Model Without Loop Query

tables:

products:

id | name | author_id    

authors:

id | name

models:

product:

public function author() {
    return $this->belongsTo('App\Author');
}

Then I get products:

$products = Product::where('name','like','username%')->get();
foreach ($products as $product) {
    $product->author;
}

Is there any way to get products with author without loop?

Ad

Answer

You need to use eager loading for this:

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