Get many to many from polymorphic table ID
Using Laravel 5.1, how can I get Dialogs
from a M:M
relationship with a Polymorphic table.
When I load tasks
, it loads the appropriate npc
. This relationship between tasks
and npcs
is a Polymorphic relation.
So I created another M:M
table, dialog_npcseventsmorphable
, that links the dialog_id
to the npcs_events_morphable_id
on npcs_events_morphable
table, but it is not loading the dialogs
.
$task = Task::findOrFail(1);
npcs_events_morphable:
id | npc_id | morphable_id | morphable_type | created_at | updated_at | published_at
----+--------+--------------+----------------+---------------------+---------------------+---------------------
1 | 1 | 1 | AppTask | 2018-05-20 04:45:24 | 2018-05-20 04:45:24 | 2018-05-20 04:45:24
2 | 2 | 1 | AppActivity | 2018-05-20 04:45:24 | 2018-05-20 04:45:24 | 2018-05-20 04:45:24
3 | 3 | 1 | AppBattle | 2018-05-20 04:45:24 | 2018-05-20 04:45:24 | 2018-05-20 04:45:24
dialog_npcseventsmorphable:
dialog_id | npcs_events_morphable_id (<-- id on 'npcs_events_morphable' table)
-----------+--------------------------
1 | 1
2 | 1
3 | 2
4 | 2
5 | 3
6 | 3
7 | 3
8 | 3
9 | 3
Task:
class Task extends BaseModel
{
protected $with = ['npcs', ...];
public function npcs()
{
return $this->morphToMany('AppNpc', 'morphable', 'npcs_events_morphable');
}
}
Npc:
class Npc extends BaseModel
{
public function tasks()
{
return $this->morphedByMany('AppTask', 'morphable', 'npcs_events_morphable');
}
...
}
Dialog:
class Dialog extends BaseModel
{
public function npcs()
{
return $this->belongsToMany(NpcsEventsMorphable::class, 'dialog_npcseventsmorphable');
}
...
}
NpcsEventsMorphable:
class NpcsEventsMorphable extends BaseModel
{
protected $table = 'npcs_events_morphable';
protected $with = ['dialogs'];
public function dialogs()
{
return $this->belongsToMany(Dialog::class, 'dialog_npcseventsmorphable');
}
}
}
from Laravel Questions and Answers https://laravelquestions.com/php/get-many-to-many-from-polymorphic-table-id/
via Lzo Media
No comments:
Post a Comment