繁体   English   中英

Laravel Eloquent属于关系返回null

[英]Laravel Eloquent belongsto relationship returns 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);
    }

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);
}

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

$posts = Post::get();

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

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

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

在此处输入图片说明

尝试指出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');
}

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

数据库中可能不存在该关系。

根据您在Post上的fillable数组,您设置关系的方式看起来是正确的,因为您遵循键的命名约定,并且您的belongsTo关系方法具有正确的约定名称。

$post->product()没有返回您的Product模型。 它返回一个Relation类型对象 ( BelongsTo )。 这用于查询关系。 $post->product将是关系的动态属性,它将返回已加载的关系或加载关系并为您提供结果。

Laravel 5.5 文档 - Eloquent - 关系 - 关系方法 Vs。 动态属性

如果关系设置正确, $post->productnull将意味着该关系实际上不存在于数据库中, product_idproduct_id products没有匹配的id为空。 (假设没有外键约束)

旁注:急切加载关系将是一个好主意:

$posts = Post::with('product')->get();

我发现我的问题在 ID = 1 的 DB 产品中没有:/ stuped 问题

感谢您为我提供的所有帮助。

我刚刚看到这篇文章是因为我在做一个项目时遇到了类似的错误。

我发现当您使用 all() 方法查询模型时,它会忽略相关的软删除行。

当您尝试访问它们时,您会得到 null

记得在关联和分离后点击 save() 。 找过我几次:

$model->relation()->associate($record)->save();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM