我有以下表格。
ID
名称
ID
名称
ID
名称
ID
event_id的
card_id的
我在Card.php以及Event.php
中添加了属于关系class Card extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function events()
{
return $this->belongsToMany(Event::class,'transfers');
}
}
class Event extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
public function user()
{
return $this->belongsTo(User::class);
}
public function cards()
{
return $this->belongsToMany(Card::class,'transfers');
}
}
我试图在我的控制器中使用以下语句,它们都返回错误
> echo count($user->events->cards->where([['id', '=',
> '57']])->find());die; //$cards is not defined.
> echo count($user->events->cards()->where([['id', '=',
> '57']])->find());die; // method cards() is not defined.I tried this after reading a tutorial
对于解决此问题的任何帮助表示赞赏。
提前致谢。
答案 0 :(得分:0)
使用hadManyThrough
关系可以让您的生活更轻松:
class User extends Model {
public function cards() {
return $this->hasManyThrough(Card::class, Event::class);
}
}
然后原则上你可以这样做:
$user->cards()->where(['id', '=', '57']);