Laravel Eloquent属于关系返回null

hai*_*som 4 php laravel eloquent laravel-5

我有两个 Eloquent 模型:

1) 发布

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);
    }
Run Code Online (Sandbox Code Playgroud)

2) 产品

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);
}
Run Code Online (Sandbox Code Playgroud)

我需要从我这样做的帖子中获取产品:

$posts = Post::get();

foreach($posts as $key){
    dd($key->product);
}
Run Code Online (Sandbox Code Playgroud)

像这样它返回 NULL 如果我这样做: dd($key->product()); 我得到了产品,但我不能使用它 在此处输入图片说明

但我需要得到类似的东西才能使用我需要的东西:

在此处输入图片说明

Ada*_*ski 11

尝试指出foregin key和其他key的关系,例子:

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

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

更多:https : //laravel.com/docs/5.5/eloquent-relationships

  • 我不知道,有时我已经遵循了 Laravel 外键名称的命名约定,但它仍然以“belongsTo”关系返回“null”。在模型名称后提及“foreign_key”可以解决这个问题。谢啦。 (2认同)