samedi 17 novembre 2018

How can I get all records belonging to the model class as relation on a 1-M polymorphic relation

I am trying to store statuses of multiple models in a polymorphic relationship and use them from there.

The retrieving of the status works but besides that I need to get all (available) the statuses belonging to that specific model. And then eager load them so I can use them in a select form or somewhere else.

Here is a representation:

// Status.php
class Status extends Model
{
    public function statusable()
    {
        return $this->morphTo();
    }
}

// Article.php
class Article extends Model
{
    public function status()
    {
        return $this->morphOne(Status::class, 'statusable', 'statusable_type', 'statusable_id', 'status');
    }
}

// Post.php
class Post extends Model
{
    public function status()
    {
        return $this->morphOne(Status::class, 'statusable', 'statusable_type', 'statusable_id', 'status');
    }
}

Here I can get the status(details) of the selected model like App\Article::first()->status()->get() or eager load it as expected. What I want is to add a method where I can call (all) statuses that belong to that particular model. For example:

$article = App\Article::first()->statuses();

and then return all available statuses to this model. I can (did) of course create a method like:

// Article.php
...
public function statuses()
{
    $statuses = Status::where('statusable_type', self::class)->get();
    return $statuses;
}

But this way I cant eager load it because I don't return a relationship. So is there a cleaner way where I can use eager loading as well?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire