Laravel 5.1属于很多不起作用的人

时间:2016-09-13 07:58:37

标签: php eloquent laravel-5.2 laravel-5.1

我有以下表格。

用户

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

对于解决此问题的任何帮助表示赞赏。

提前致谢。

1 个答案:

答案 0 :(得分:0)

使用hadManyThrough关系可以让您的生活更轻松:

class User extends Model {
     public function cards() {
          return $this->hasManyThrough(Card::class, Event::class);
     }    
} 

然后原则上你可以这样做:

$user->cards()->where(['id', '=', '57']);