Laravel Eloquent with () & # 8594; returns null

I'm trying to use Eloquent to get a specific product with a brand_id column that maps to the brands table, the brand array is returned empty.

Is there something obvious here that needs to be changed?

 $product = Product::with('images')->with('brand')->select($fields)->where('display', '=', 1)->find($id); 

// Product Model

 class Product extends Eloquent { ... public function brand() { return $this->belongsTo('Brand'); } 

// Brand Model

 class Brand extends Eloquent { ... public function products() { return $this->hasMany('Product'); } 
+6
source share
1 answer

You have the following:

 $product = Product::with('images', 'brand') ->select($fields) ->where('display', 1) ->find($id); 

You get null for brand , and this may be because you have certain fields and most likely you did not select foreing_key from the products table, which creates a link to brand , so if your products table contains a foreign_key table (maybe brand_id ) of the brand table, then you must select this foreign_key from the products table. Therefore, add only foreign_key/brand_id to the $fields variable. Without a relationship linker ( FK ) key, the brand will not be loaded.

+9
source

Source: https://habr.com/ru/post/970591/


All Articles