morphtoMany不使用指定的变形键

时间:2018-01-27 16:27:18

标签: laravel laravel-5 laravel-5.5

所以,我有一个事件表,用户可以“去”或“感兴趣”,很多用户都可以去。 (对于这个例子,我们只是在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_participantsowner_idpivot_owner_id,   event_participantsevents_idpivot_events_id,   event_participantsowner_typepivot_owner_type,   event_participantsstatuspivot_status,   来自event_participants的{​​{1}}。created_atpivot_created_at   events上的内部联接event_participantsevents =   idevent_participants其中events_idevent_participants   = 9和owner_idevent_participants = App \ Modules \ Account \ Entities \ User和owner_typeevent_participants =   2)

从Laravel文档中,它指定要变形的类,键和表(可选)

关系https://laravel.com/docs/5.5/eloquent-relationships

为什么我的代码不遵守他的规则?我该如何解决这个问题?

1 个答案:

答案 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');
}