繁体   English   中英

Laravel 5.1属于许多无法正常工作

[英]Laravel 5.1 belongs to many not working

我有下表。

用户数

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

感谢您对解决此问题的任何帮助。

提前致谢。

通过使用hadManyThrough关系,可以使您的生活更加轻松:

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

然后原则上您可以执行以下操作:

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

暂无
暂无

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

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