Mysql 加载带有递归条件的多态模型
我试图加载一个多态模型,其中包含一些条件,这些条件与另外两个模型相连,并且存在一些问题 我的模型:Mysql 加载带有递归条件的多态模型,mysql,laravel-5,laravel-5.2,Mysql,Laravel 5,Laravel 5.2,我试图加载一个多态模型,其中包含一些条件,这些条件与另外两个模型相连,并且存在一些问题 我的模型: class One extends Model { public function twos() { return $this->hasMany(Two::class); } public function threes() { return $this->morphMany(Three::class, 'threeable'
class One extends Model {
public function twos() {
return $this->hasMany(Two::class);
}
public function threes() {
return $this->morphMany(Three::class, 'threeable');
}
}
class Two extends Model {
public function one() {
return $this->belongsTo(One::class);
}
public function threes() {
return $this->morphMany(Three::class, 'threeable');
}
}
class Three extends Model {
public function threeable() {
return $this->morphTo();
}
}
到目前为止,一切都很好:我有很多One
项目,它们有很多Two
关系,而且两者都有更多的Two
关系(单独)
现在,我尝试从Two
中获取最新的Two
,其中它也可以来自One
关系(最高的三个从a或B更新)
三人桌看起来像这样
| id | threeable_id | threeable_type | updated_at |
|---|---|---|---|
| 1 | 1 | A | 1 |
| 2 | 1 | A | 2 |
| 3 | 1 | B | 3 |
| 4 | 1 | B | 4 |
| 5 | 2 | A | 2 |
| 6 | 2 | A | 4 |
| 7 | 2 | B | 1 |
| 8 | 2 | B | 3 |
我想要三个s.id=4表示B::find(1)->withC()
和三个s.id=6表示B::find(2)->withC()
出于性能原因,我希望在一个查询中加载它(我正在加载多个2
,并且希望相关的3
,而不希望为此启动自己的查询)。所以我试着把它放在一个范围内(在classTwo
中)。加入Three
表,并在子查询中对更新的\u at执行一些max。。。这是一个完全混乱,并没有很好地工作
它也没有真正感受到“拉雷维尔方式”:(
谢谢你的帮助
编辑
也许作为一个补充,这里是纯SQL
SELECT twos.id, threes.id
FROM
(SELECT
twos.id twoId, MAX(th.updated_at) threeMaxUA
FROM
twos
LEFT JOIN (SELECT
th.*
FROM
(SELECT
threeable_id, threeable_type, MAX(updated_at) AS updated_at
FROM
threes
WHERE
deleted_at IS NULL
GROUP BY threeable_id , threeable_type) thmax
LEFT JOIN
threes pr ON (th.threeable_id = thmax.threeable_id
AND th.updated_at = thmax.updated_at
AND th.threeable_type = thmax.threeable_type)
GROUP BY th.threeable_id , th.threeable_type) th
ON
(
(th.threeable_id = twos.id AND th.threeable_type = 'App\\Two')
OR
(th.threeable_id = twos.product_id AND th.threeable_type = 'App\\One')
)
GROUP BY twos.id
) twthmax
LEFT JOIN twos ON twos.id = twthmax.twoId
LEFT JOIN threes ON (
twthmax.threeMaxUA = threes.updated_at
AND
(
(threes.threeable_id = twos.id AND threes.threeable_type = 'App\\Two')
OR
(threes.threeable_id = twos.product_id AND threes.threeable_type = 'App\\One')
)
)