Get array of Eloquent model's relations

后端 未结 2 1356
旧时难觅i
旧时难觅i 2020-12-29 03:41

I\'m trying to get an array of all of my model\'s associations. I have the following model:

class Article extends Eloquent 
{
    protected $guarded = array(         


        
2条回答
  •  有刺的猬
    2020-12-29 04:01

    It's not possible because relationships are loaded only when requested either by using with (for eager loading) or using relationship public method defined in the model, for example, if a Author model is created with following relationship

    public function articles() {
        return $this->hasMany('Article');
    }
    

    When you call this method like:

    $author = Author::find(1);
    $author->articles; // <-- this will load related article models as a collection
    

    Also, as I said with, when you use something like this:

    $article = Article::with('author')->get(1);
    

    In this case, the first article (with id 1) will be loaded with it's related model Author and you can use

    $article->author->name; // to access the name field from related/loaded author model
    

    So, it's not possible to get the relations magically without using appropriate method for loading of relationships but once you load the relationship (related models) then you may use something like this to get the relations:

    $article = Article::with(['category', 'author'])->first();
    $article->getRelations(); // get all the related models
    $article->getRelation('author'); // to get only related author model
    

    To convert them to an array you may use toArray() method like:

    dd($article->getRelations()->toArray()); // dump and die as array
    

    The relationsToArray() method works on a model which is loaded with it's related models. This method converts related models to array form where toArray() method converts all the data of a model (with relationship) to array, here is the source code:

    public function toArray()
    {
         $attributes = $this->attributesToArray();
    
         return array_merge($attributes, $this->relationsToArray());
    }
    

    It merges model attributes and it's related model's attributes after converting to array then returns it.

提交回复
热议问题