【发布时间】: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
我不知道应该去哪里解决这个问题。我已经看过了
https://github.com/laravel/framework/issues/2093#issuecomment-39154456
Using pivot model data as a relationship to another model in Laravel 4's Eloquent
但这并没有解决我的问题。
有什么想法吗?或者 Eloquent 不可能做到这一点?
【问题讨论】:
-
你成功了吗?
标签: php laravel pivot eloquent relationship