2014-02-12 25 views
3

这时候在指定的列是一个后续帖子:Laravel 4 and Eloquent: retrieving all records and all related recordsLaravel和雄辩:检索相关项目

给出的解决方案的伟大工程:

$artists = Artist::with('instruments')->get(); 
return \View::make('artists')->withArtists($artists); 

它还适用于刚:

$artists = Artist::get(); 

现在我试图指定两个表返回的确切列。我在上面和在我的课的语句中使用select()试过了,是这样的:

ArtistController.php

$artists = Artist::select('firstname', 'lastname', 'instruments.name')->get(); 

或:

$artists = Artist::with(array('instruments' => function($query) { 
    $query->select('name'); 
}))->get(); 

(如建议here同时这不会引起错误,它也不会将列限制为仅指定那些列)

Artist.php

return $this->belongsToMany('App\Models\Instrument')->select(['name']); 

我将如何去获得只是firstnamelastname列从artists表和instrumentsname列?

+1

你的问题是你必须加载主键和外键。否则,ORM无法加载你的关系。 –

+0

@JosephSilber您的评论帮助了我!所以,在知识中生活愉快,你已经帮助至少一个人发展了! :] – Azirius

回答

3

不知道我在想什么。我认为,这么长时间的工作让我有了独眼。

无论如何,我仔细研究了这个问题并搜索了答案,最后在GitHub上发布了一个问题。

底线是而不是可能的Laravel v4.1。

https://github.com/laravel/laravel/issues/2679

这解决了这个问题:

Artists.php

public function instruments() { 
    return $this->hasMany('App\Models\Instrument', 'id'); 
} 

注意,我从一个belongsToMany这让我更有意义的改变了这种为hasMany音乐家(或Artist)会有许多Instrument他们玩和Instrument可能属于很多Artist s(我在前面提到的问题中也提到过)。我还必须在我的模型中指定'id'列,该列告诉ORM instrument.id匹配artist_instrument.id。这部分让我感到困惑,因为我认为hasMany的订单是foreign_key,primary_key,但也许我正在考虑向后。如果有人能解释一点,我会很感激。

总之,该解决方案的第二部分...

ArtistsController.php,我这样做:

$artists = Artist::with(array(
    'instruments' => function($q) { 
     $q->select('instruments.id', 'name'); 
    }) 
)->get(array('id', 'firstname', 'lastname')); 

这给了我正是我想要的是艺术家的集合其中仅包含播放的每个乐器的 firstnamelastname列以及 artists表和 name列。

+0

“当前不支持限制belongsToMany关系中的列。” –

2
$artists = Artist::with(array('instruments' => function ($query) { 
    $query->select('id', 'name'); 
}))->get('id', 'firstname', 'lastname'); 
+0

这会引发错误,说明“id”列不明确。如果我这样做:'instruments.id'和'artists.id',那么它不会失败,但它不会限制列。在这种情况下,'instruments.id'是'artist_instrument'中'instrument_id'的外键,'artists.id'是'artist_instrument'中'artist_id'的外键。 – tptcat