Laravel口才所属关系返回null [英] Laravel Eloquent belongsto relationship returns null
本文介绍了Laravel口才所属关系返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个雄辩的模型:
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);
}
我需要从帖子
中获取产品:
I need to get the product from a post I do that:
$posts = Post::get();
foreach($posts as $key){
dd($key->product);
}
就像这样,它返回NULL
如果我这样做:
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
但是我需要得到类似的东西才能使用我需要的东西:
but I need to get something like that to use whant I need:
推荐答案
尝试指出前向键和其他键相对而言,示例:
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');
}
更多: https://laravel.com/docs/5.5/eloquent-relationships
这篇关于Laravel口才所属关系返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文