2016-10-13 12 views
0

の特定の列を選択します。私は、著者の機能を持たせて、私のポストモデルでは著者とポストLaravel 5雄弁:私は2つの機種持っている関係

を(多くの(逆に1を)):

public function author() 
    { 
     return $this->belongsTo('App\Author', 'author_id'); 
    } 

今度は、Excelに以下の情報をエクスポートします:

id |タイトル|著者名

これは私が試したものです:

$posts = Post::with(array(
     'author' => function ($query) { 
      $query->select('name'); 
     }))->select('id', 'title')->get(); 

私は何を取得することは、空の著者名の欄です。

どうしますか?

+0

- > select( 'id'、 'title') - > get();の代わりにget( 'id AS Id'、 'title AS Title'、 'authors.name AS Name' – t9toqwerty

答えて

2

てみてください。

$posts = Post::with(['author' => function($query){ 
    $query->select(['id','name']); 
}])->get(['id','title', 'author_foreign_key_in_posts_table']); 

はそれを持って、あなたが得ることができるでしょう:

$posts->first()->author->name; 
$posts->first()->id; 
$posts->first()->title; 

あなたは反復を使用することができますまたは任意の代わりに、最初の()輸出用。

関連する問題