I try to eager load a polymorphic model with some conditions that's connected to two other models and having some problems.
My models:
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();
}
}
So far everythings is everything great: I've a lot of One
items that have a lot of Two
relations and both have even more Three
relations (on its own).
Now I try to get the latest Three
from Two
, where it also can come from a One
relation (highest threes.updated_at from either A or B).
The threes table looks something like this
| 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 |
I want threes.id = 4 for B::find(1)->withC()
and threes.id = 6 for B::find(2)->withC()
.
For performance reasons I want to load it in one query (I'm loading multiple Two
and want the related Three
and don't want to fire an own query for that). So I tried to put it in a scope (in class Two
). Joining on the Three
table and doing some max on the updated_at in a sub query ... It was a total mess and didn't worked that well
It didn't really feel the "Laravel-way" neither :(
Thanks for any help
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1WXzh2M
via IFTTT
Aucun commentaire:
Enregistrer un commentaire