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
归档时间: |
|
查看次数: |
22857 次 |
最近记录: |