从本Laravel 5.1文档中,我似乎可以在HasMany关系上使用以下内容覆盖foreign_key和local_key:
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');我将belongsTo模型NpcTarget中的外键从npc_id改为npc_id_fk。因此,我将关系改为:
public function npc()
{
return $this->belongsTo(Npc::class, 'npc_id_fk', 'id');
}npc_id_fk引用npc的外键id,id是npc中列的实际名称。
--我的目标是--用task和npc以及npctarget加载quest。运行我自己的查询就像预期的那样:
select n.id, nt.id from npcs n inner join npcstarget nt on (n.id = nt.npc_id_fk);Problem:给定下面的关系,当我运行它时,浏览器会超时。我得到了错误:
FatalErrorException在QueryCollector.php第0行中: 超过30秒的最大执行时间
然而,如果我更改为return $this->belongsTo(Npc::class, 'npc_id_fk', 'npc_id');,它将运行查询where "npcstarget"."npc_id_fk" in ('')。为什么浏览器超时?
使用定义为NpcTarget关系的$this->belongsTo(Npc::class, 'npc_id_fk', 'npc_id');执行以下路由
Route::get('/quest', function () {
$quest = Quest::findOrFail(1)->get();
});我得到DebugBar输出:
select * from "quests" where "quests"."id" = '1' limit 1
select * from "tasks" where "tasks"."quest_id" in ('1')
select "npcs".*, "task_npcs"."task_id" as "pivot_task_id", "task_npcs"."npc_id" as "pivot_npc_id" from "npcs" inner join "task_npcs" on "npcs"."id" = "task_npcs"."npc_id" where "task_npcs"."task_id" in ('1', '2', '3')
select * from "npcstarget" where "npcstarget"."npc_id_fk" in ('')使用NpcTarget关系定义为$this->belongsTo(Npc::class, 'npc_id_fk', 'id');的同一条路径,在没有查询输出的情况下超时。
模型:
探索:
class Quest extends BaseModel
{
protected $with = ['tasks'];
public function tasks()
{
return $this->hasMany(Task::class);
}
...
}任务:
class Task extends BaseModel
{
protected $with = ['npcs'];
public function npcs()
{
return $this->belongsToMany(Npc::class, 'task_npcs');
}
...
}全国人大:
class Npc extends BaseModel
{
protected $with = ['npcstarget'];
public function npcstarget()
{
return $this->hasMany(NpcTarget::class, 'npc_id_fk', 'id');
}
}NpcTarget:
class NpcTarget extends Npc
{
protected $table = 'npcstarget';
public function npc()
{
// If this: Times out
return $this->belongsTo(Npc::class, 'npc_id_fk', 'id');
// If this: Shows above "where "npcstarget"."npc_id_fk" in ('')"
return $this->belongsTo(Npc::class, 'npc_id_fk', 'npc_id');
}
}发布于 2018-05-16 02:52:03
似乎错误是NpcTarget扩展了Npc
class NpcTarget extends Npc
{
protected $table = 'npcstarget';
public function npc()
{
// If this: Times out
return $this->belongsTo(Npc::class, 'npc_id_fk', 'id');
}
}将其更改为class NpcTarget extends BaseModel有效。
我猜这是因为扩展Npc调用了NpcTarget上的另一个with查询,从而创建了一个无限循环。
我仍然希望扩展父模型以获得它的一些属性。
https://stackoverflow.com/questions/50361687
复制相似问题