I have a Model Text
which has a 1-to-many-relation called pretext()
, returning a 1-to-many-Relationshop to Text
, like so:
class Text extends Model
{
public function pretext(){
return $this->belongsTo('App\Models\Text', 'pretext_id');
}
public function derivates(){
return $this->hasMany('App\Models\Text', 'pretext_id');
}
}
If a $text
does not have any pretext (which, in my scenario, means $text['pretext_id'] == 0
) $text->pretext() shall return the $text
itself. When I try
public function pretext(){
if ( $this->belongsTo('App\Models\Text', 'pretext_id') ) {
return $this->belongsTo('App\Models\Text', 'pretext_id');
}
else {
return $this;
}
}
I get the error
local.ERROR: LogicException: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
when the else-part is executed. So my questions are:
- How do I turn $this into an object of type Relation? or alternatively:
- How can I achieve my goal on a different way?
$this
into a Relation. I suggest you check everytime if theText
has aPretext
or not :$text->pretext ? "Has pretext" : "No pretext";
. – Treastif/else
, then make a separate function that returns either the relation, or itself. Laravel functionality depends on a relation function returning a relation, so you should just wrap the function separately with your custom logic. – Jeff