Answer the question
In order to leave comments, you need to log in
How to load different relationships for morphs relationships?
It’s even difficult for me to form a question, so it’s better to immediately look at the code example.
How to load relations depending on object type in mophs table?
class SomeModelFirst extends Model
{
public function notes()
{
return $this->morphMany(App\Note::class, 'noteable');
}
public function relationFirst()
{
return $this->belongsTo(Photo::class);
}
}
class SomeModelSecond extends Model
{
public function notes()
{
return $this->morphMany(App\Note::class, 'noteable');
}
public function relationSecond() {
return $this->belongsToMany(Comment::class);
}
}
class Note extends Model
{
public function noteable()
{
return $this->morphTo();
}
}
Представим, что в таблице есть noteable_to с SomeModelFirst и SomeModelSecond
$notes = Notes::with('noteable', 'noteable.relationFirst', 'noteable.relationSecond');
// будет ошибка, т.к. у SomeModelFirst нет relationSecond и у SomeModelSecond нет relationFirst.
Как быть?
Answer the question
In order to leave comments, you need to log in
There are at least three ways to do this.
in Orthodox
in bourgeois
class Note extends Model
{
public function second()
{
return $this->morphedByMany(SomeModelSecond::class, 'taggable');
}
public function first()
{
return $this->morphedByMany(SomeModelFirst::class 'taggable');
}
}
class SomeModelFirst extends Model
{
public $with = ['relationFirst'];
public function notes()
{
return $this->morphMany(App\Note::class, 'noteable');
}
public function relationFirst()
{
return $this->belongsTo(Photo::class);
}
}
class SomeModelSecond extends Model
{
public $with = ['relationSecond']
public function notes()
{
return $this->morphMany(App\Note::class, 'noteable');
}
public function relationSecond() {
return $this->belongsToMany(Comment::class);
}
}
$notes = Notes::with('noteable');
$notesGrouped = $noted->groupBy(function($model){
return get_class($model);
});
$notesGrouped[SomeModelFirst::class]->load('relationFirst');
$notesGrouped[SomeModelSecond ::class]->load('relationSecond');
Well, I don't think magic will help much here. Either any noteable extends some abstract class that implements dummy relays, or separate noteable into someModelFirst(), someModelSecond() and load it according to separate conditions.
Of course, you can pervert and override the method responsible for finding the relay - but this is nonsense, you don’t need to do this =)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question