Tob*_*b0t 5 php pivot relationship laravel eloquent
如何将关系添加到枢轴模型?
我有以下表格:
users
-id
events
-id
user_event
-id
-user_id
-event_id
tickets
-price
-user_event_id
Run Code Online (Sandbox Code Playgroud)
所以一个用户可以访问多个事件,一个事件属于多个用户。现在我希望用户可以拥有一个特殊活动的许多不同门票。
我的模型如下:
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);
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
use Illuminate\Database\Eloquent\Relations\Pivot;
class UserEvent extends Pivot{
protected $table = 'user_event';
public function tickets() {
return $this->hasMany('Ticket');
}
}
Run Code Online (Sandbox Code Playgroud)
class Ticket extends Eloquent{
// Joins
public function getUserEvent(){
return $this->belongsTo('user_event','user_event_id');
}
Run Code Online (Sandbox Code Playgroud)
现在我想列出一个特定用户到一个特定事件的第一张票:我尝试了以下操作:
$event->first()->getUsers->first()->pivot->tickets->first();
Run Code Online (Sandbox Code Playgroud)
但我收到一条错误消息:
Call to a member function first() on a non-object
Run Code Online (Sandbox Code Playgroud)
我不知道我应该在哪里解决这个问题。我已经看过了
但它没有解决我的问题。
有任何想法吗?或者 Eloquent 不可能做到这一点?
您收到的错误可能是由某些拼写错误引起的(->getUsers->first()我想是部分),因为您粘贴的代码unknown column event_id在到达->tickets部分时应该抛出数据库错误。
所以首先解决这个问题,然后:
为了使其工作,您需要在关系中指定外键,因为 Eloquent 使用在类getForeignKey()上覆盖的外键来猜测它Pivot并返回不同的值(event_id在本例中):
class UserEvent extends Pivot{
protected $table = 'user_event';
public function tickets() {
return $this->hasMany('Ticket', 'user_event_id');
}
}
Run Code Online (Sandbox Code Playgroud)