所以,我有一个事件表,用户可以“去”或“感兴趣”,很多用户都可以去。 (对于这个例子,我们只是在Events类上使用它。
所以,我这样指定变形:
/**
* Get the user's events they're interested in
*
* @return builder
*/
public function interested($class = __CLASS__)
{
return $this->morphToMany($class, 'owner', EventParticipants::table)
->wherePivot('status', '=', EventParticipants::INTERESTED)
->withPivot('owner_type', 'status', 'created_at');
}
这是我的用户模型中的特征。
他们代表什么:
$class = "App\Modules\Events\Entities\Events"
'owner' = the key I want to use, because my DB has owner_id and owner_type
EventParticipants::table = 'event_participants'
EventParticipants::INTERESTED = "interested"
我可以有多种状态(去,感兴趣..)我的数据库结构是这样的:
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('event_participants', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('owner_id');
$table->string('owner_type');
$table->string('status')->default('pending')->comment('pending/going/interested');
$table->timestamps();
});
}
我的示例数据:
INSERT INTO `social`.`event_participants`
(`id`,
`user_id`,
`owner_type`,
`owner_id`,
`status`,
`created_at`,
`updated_at`)
VALUES
('14',
'9',
'App\\Modules\\Events\\Entities\\Events',
'1',
'2',
'2018-01-27 14:19:03',
'2018-01-27 14:19:03');
但是变形特征没有使用我在错误中看到的指定owner
键:
SQLSTATE [42S22]:找不到列:1054未知列 '字段列表'中的'event_participants.events_id'(SQL:select
events
。*,event_participants
。owner_id
为pivot_owner_id
,event_participants
。events_id
为pivot_events_id
,event_participants
。owner_type
为pivot_owner_type
,event_participants
。status
为pivot_status
, 来自event_participants
的{{1}}。created_at
为pivot_created_at
events
上的内部联接event_participants
。events
=id
。event_participants
其中events_id
。event_participants
= 9和owner_id
。event_participants
= App \ Modules \ Account \ Entities \ User和owner_type
。event_participants
= 2)
从Laravel文档中,它指定要变形的类,键和表(可选)
关系:https://laravel.com/docs/5.5/eloquent-relationships
为什么我的代码不遵守他的规则?我该如何解决这个问题?
答案 0 :(得分:0)
所以,我正在使用morphToMany
,这是变形的,而不是morphedByMany
我使用以下方法解决了我的问题:
<强>之前:强>
/**
* Get the user's events they're interested in
*
* @return builder
*/
public function interested($class = __CLASS__)
{
return $this->morphToMany($class, 'owner', EventParticipants::table)
->wherePivot('status', '=', EventParticipants::INTERESTED)
->withPivot('owner_type', 'status', 'created_at');
}
<强>后:强>
/**
* Get the user's events they're interested in
*
* @return builder
*/
public function interested($class = __CLASS__)
{
return $this->morphedByMany($class, 'owner', EventParticipants::table)
->wherePivot('status', '=', EventParticipants::INTERESTED)
->withPivot('owner_type', 'status', 'created_at');
}