小编hai*_*som的帖子

Laravel Eloquent属于关系返回null

我有两个 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()); 我得到了产品,但我不能使用它 在此处输入图片说明

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

在此处输入图片说明

php laravel eloquent laravel-5

4
推荐指数
1
解决办法
2万
查看次数

标签 统计

eloquent ×1

laravel ×1

laravel-5 ×1

php ×1