Problems with the with () method in Laravel

1

I'm doing the following query.

$Products = Product::with('productFiles')->where("name", "like", "%{$request->value}%")->limit(10)->get();

This query calls all the products and an array called "productFiles" WITH DATA. But if I add a select as the following, the array "productFiles" is empty.

$Products = Product::select('name', 'slug')->with('productFiles')->where("name", "like", "%{$request->value}%")->limit(10)->get();

I must clarify that productFiles is a method of the Product model, it is declared like this.

public function productFiles(){
    return $this->hasMany(ProductFile::class);
}

Thanks for your help!

    
asked by Santiago Ruiz 05.05.2016 в 20:33
source

1 answer

0

You can create a callback, where you send the query and add the whereRaw of productFile and the addSelect with the names of the columns of the relationship table that you need. When you get it with - > get () you send the columns of the table producut

$Products = Product::with(['productFiles' => function($q){
  $q->addSelect(['name'])
  ->whereRaw('"name", "like", "%{$request->value}%""')
  ->limit(10);
}])->get(['name', 'slug']);
    
answered by 05.05.2016 / 22:20
source