Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent belongsto relationship returns null

I have two Eloquent models:

1) Post

class Post extends Model
{
    protected $table = 'posts';
    protected $fillable = ['id', 'user_id', 'product_id', 'site_id', 'link_id', 'body', 'created_at', 'updated_at'];

    public function user(){
        return $this->belongsTo(User::class);
    }

    public function product(){
        return $this->belongsTo(Product::class);
    }

2) Product

protected $table = 'products';
protected $fillable = ['id', 'user_id', 'manufacturer_id', 'shift_product_id', 'name', 'english_name',
                        'slug', 'text', 'spec', 'live', 'created_at', 'updated_at'];

public function posts(){
    return $this->hasMany(Post::class);
}

I need to get the product from a post I do that:

$posts = Post::get();

foreach($posts as $key){
    dd($key->product);
}

Like this it returns NULL If I do like this: dd($key->product()); I get the product but I can't to use that enter image description here

but I need to get something like that to use whant I need:

enter image description here

like image 306
haisom Avatar asked Dec 01 '22 11:12

haisom


2 Answers

Try to point out foregin key and other key in relation, examples:

public function post()
{
    return $this->belongsTo('App\Post', 'foreign_key', 'other_key');
}

public function user()
{
    return $this->belongsTo('App\User', 'foreign_key', 'other_key');
}

More: https://laravel.com/docs/5.5/eloquent-relationships

like image 161
Adam Kozlowski Avatar answered Dec 04 '22 08:12

Adam Kozlowski


i found my problem i dont have in the DB product with ID = 1 :/ stuped problem

thanks for all the help i leran alot from u.

like image 23
haisom Avatar answered Dec 04 '22 09:12

haisom