Laravel: 向中间模型添加关联关系

13 浏览
0 Comments

Laravel: 向中间模型添加关联关系

如何向枢纽模型添加关系?

我有以下表格:

users
-id
events
-id
user_event
-id
-user_id
-event_id
tickets
-price
-user_event_id

因此,一个用户可以参加多个事件,而一个事件可以属于多个用户。现在,我希望一个用户可以为一个特定的事件拥有多个不同的门票。

我的模型如下:

Event:

class Event extends Eloquent{
    // 连接
    public function getUsers(){
        return $this->belongsToMany('User', 'user_event', 'event_id', 'user_id')->withPivot('id', 'emailSent', 'info')->withTimestamps();
    }
    // 枢纽
    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);
    }

User:

class User extends Eloquent implements UserInterface, RemindableInterface {
    // 连接
    public function getEvents(){
        return $this->belongsToMany('Event', 'user_event', 'user_id', 'event_id')->withPivot('id', 'emailSent', 'info')->withTimestamps();
    }
    // 枢纽
    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);
    }

UserEvent

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

Ticket

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

现在,我想列出一个特定用户对一个特定事件的第一个票:

我尝试了以下代码:

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

但我收到了一个错误消息:

在非对象上调用成员函数first()

我不知道我应该在哪里寻找解决这个问题的方法。我已经查看了以下内容:

但这没有解决我的问题。

有什么想法吗?或者Eloquent不支持这个功能吗?

0
0 Comments

Laravel:向中间表模型添加关联关系

在你提供的代码中,你可能会遇到一些拼写错误导致的错误(我猜是`->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'); 
    }
}

非常感谢你,先生。我想知道是否可以通过这种解决方案来实现我在这里提到的情况。我可以请教您一些问题吗,亲切的先生?

0