在laravel中获取具有Eloquent关系的列列表
问题描述:
I want to get column list with Eloquent relation in laravel. When I use this comman
$columns = Schema::getColumnListing('news');
Result is all fields of news table but I want to get relation fields for CategoryNews table.
News model:
public function NewsCategories()
{
return $this->belongsTo('App\CategoryNews');
}
CategoryNews model:
public function News()
{
return $this->hasMany('App\News');
}
答
You should be able to do something like this:
$columns = Schema::getColumnListing($news->NewsCategories()->getRelated()->getTable()));
Using getRelated()
method you are getting related object for relationship (in your case it's App\CategoryNews
) and now using method getTable()
you can get table name for this model and you can use this table name for getColumnListing()
method.