Get array of Eloquent model's relations

后端 未结 2 1378
旧时难觅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:10

    use this:

    class Article extends Eloquent 
    {
        protected $guarded = array();
    
        public static $rules = array();
    
        public $relationships = array('Author', 'Category');
    
        public function author() {
            return $this->belongsTo('Author');
        }
    
        public function category() {
            return $this->belongsTo('Category');
        }
    }
    

    So outside the class you can do something like this:

    public function articleWithAllRelationships()
    {
        $article = new Article;
        $relationships = $article->relationships;
        $article = $article->with($relationships)->first();
    }
    

提交回复
热议问题