【问题标题】:Laravel: Adding relationships to a pivot modelLaravel:向枢轴模型添加关系
【发布时间】:2014-08-17 10:43:08
【问题描述】:

如何向数据透视模型添加关系?

我有以下表格:

users
-id

events
-id

user_event
-id
-user_id
-event_id

tickets
-price
-user_event_id

所以一个用户可以访问多个事件,一个事件属于多个用户。现在我希望用户可以为一个特殊活动拥有许多不同的门票。

我的模型如下:

事件:

class Event extends Eloquent{
    // Joins
    public function getUsers(){
        return $this->belongsToMany('User', 'user_event', 'event_id', 'user_id')->withPivot('id', 'emailSent', 'info')->withTimestamps();
    }
    // Pivot
    public function newPivot(Eloquent $parent, array $attributes, $table, $exists) {
       if ($parent instanceof User) {
            return new UserEvent($parent, $attributes, $table, $exists);
       }
       return parent::newPivot($parent, $attributes, $table, $exists);
    }

用户:

class User extends Eloquent implements UserInterface, RemindableInterface {
    //Joins  
    public function getEvents(){
        return $this->belongsToMany('Event', 'user_event', 'user_id', 'event_id')->withPivot('id', 'emailSent', 'info')->withTimestamps();
    }


    // Pivot
    public function newPivot(Eloquent $parent, array $attributes, $table, $exists) {
        if ($parent instanceof Event) {
            return new UserEvent($parent, $attributes, $table, $exists);
        }
        return parent::newPivot($parent, $attributes, $table, $exists);
    }

用户事件

use Illuminate\Database\Eloquent\Relations\Pivot;

class UserEvent extends Pivot{
    protected $table = 'user_event';
    public function tickets() {
        return $this->hasMany('Ticket'); 
    }
}

门票

class Ticket extends Eloquent{
    // Joins
    public function getUserEvent(){
        return $this->belongsTo('user_event','user_event_id');
    }

现在我想列出一个特定用户对一个特定事件的第一张票: 我尝试了以下方法:

$event->first()->getUsers->first()->pivot->tickets->first();

但我收到一条错误消息:

Call to a member function first() on a non-object

我不知道应该去哪里解决这个问题。我已经看过了

但这并没有解决我的问题。

有什么想法吗?或者 Eloquent 不可能做到这一点?

【问题讨论】:

  • 你成功了吗?

标签: php laravel pivot eloquent relationship


【解决方案1】:

您得到的错误可能是由某些拼写错误引起的(我猜是->getUsers->first() 部分),因为您粘贴的代码在到达->tickets 部分时应该抛出DB 错误unknown column event_id

所以先解决这个问题,然后:

要使其工作,您需要在关系中指定外键,因为 Eloquent 使用 getForeignKey() 猜测它,它在 Pivot 类上被覆盖并返回不同的值(在这种情况下为 event_id):

class UserEvent extends Pivot{
    protected $table = 'user_event';
    public function tickets() {
        return $this->hasMany('Ticket', 'user_event_id'); 
    }
}

【讨论】:

  • 晚安,先生。我想知道我的案例here 是否可以通过这种解决方案实现。亲爱的先生,我可以向您寻求帮助吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
  • 2018-05-16
  • 2021-08-25
  • 2021-01-07
  • 2020-08-23
相关资源
最近更新 更多