Laravel eloquent model how to get data from relationship's table Laravel eloquent model how to get data from relationship's table laravel laravel

Laravel eloquent model how to get data from relationship's table


Yes, you can get the details of the products and skus without making one additional query per product using eager loading ( this is referred as the typical N+1 query problem where N is the number of the products )

Suppose the relation between your Product and Sku models model is:

Product

public function skus(){    return hasMany('App/Sku','products_id');}

To fetch the products data along with the sku data you can use the with method. In your controller:

Controller

 $products = Product::with('skus')->get();

Then, in your views, you can get the info this way:

View

foreach ($products as $product) {     //$product->skus is a collection of Sku models     dd( $product->skus );}

For the repository question: if you want to use a repository you can place the eloquent-access part of your code inside the repository. So, for example you could have this method inside the repository:

ProductRepository

public function getProductsData() {    //access eloquent from the repository    return Product::with('skus')->get();    } 

then you can use your repository in your controller:

Controller

//inject the repository in the controllerpublic function __construct( ProductRepository $productRepo ){    $this->productRepo = $productRepo;}//use the injected repository to get the datapublic function index(){    $products = this->productRepo->getProductsData();}


If I understand your question correctly, you can use eager loading.

 public function index() {    $products = Product::with('skus')->get(); }

This will give you an array of products that have a skus array in each product object.


If the repository pattern is used, do it like this.

public function index() {    $data = $this->passportRepository->with('user')->findWhere(['id'=>1]);}