Laravel 4和Eloquent:检索所有记录和所有相关记录

3

我有两个类:艺术家乐器,每个艺术家可以演奏一个或多个乐器,而每个乐器也可以分配给一个或多个艺术家。因此,我已经创建了以下类:

Artist.php

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

Instrument.php

public function artists() {
    return $this->belongsToMany('\App\Models\Artist');
}


接下来有三个数据库表:

artists: id, firstname, lastname, (timestamps)
instruments: id, name
artist_instrument: id, artist_id, instrument_id
我可以成功地检索到一个艺术家及其相关乐器,代码如下:

ArtistController.php

$artist = Artist::find($artist_id);
$instruments = $artist->instruments()->get();
return \View::make('artists')->with('artists', $artists)->with('instruments', $instruments);

我有三个问题:

  1. In my view, I can output the $artist like:

    {{ $artist->firstname }}
    

    and I can iterate through $instruments like:

    @foreach ($instruments as $instrument)
        <h2>{{ $instrument->name }}</h2>
    @endforeach
    

    but is it possible to iterate over $artist (I know there's only one — see #2) and for each $artist iterate over their $instruments?

  2. In my controller, how would I get all artists and for each of those their associated instruments with the end goal of iterating through them in my view as described in #1.

  3. Is it possible to only retrieve specific columns in the above example of ArtistController.php? I've tried this:

    $artist = Artist::where('id', $artist_id)->get('firstname');
    $instruments = $artist->instruments()->get();
    return \View::make('artists')->with('artists', $artists)->with('instruments', $instruments);
    

    but I get an error saying Collection::instruments() is undefined.

我猜测我的模型关系存在问题。我也尝试在 Artist.php 中使用 hasMany 定义我的关系(我认为“每个艺术家都有多个乐器”更有意义),但这会给我带来一个错误,因为它期望一个名为 artists_instruments 的表,并且还试图检索该表中不存在的列(例如 name)。


1
尝试在->get('firstname')中包含您的艺术家关系键(我假设它将是'id',就像这样:->get('id','firstname')) - Patrick
1个回答

11

你的模型关系很好。

控制器:

$artists = Artist::with('instruments')->get();

return \View::make('artists')->withArtists($artists);

查看:

@foreach ($artists as $artist)

    <h1>{{ $artist->firstname }}</h1>

    @foreach ($artist->instruments as $instrument)

        <h2>{{ $instrument->name }}</h2>

    @endforeach

@endforeach

2
我刚看到你的回复,恰好我也找到了答案。非常感谢! - tptcat
还有一件事(如果有意义,我可以将其作为单独的问题发布),如果我不想检索所有列,我该如何指定要检索的列?我尝试在各个地方使用select(),但似乎没有起作用。 - tptcat
@tptcat - 这绝对应该是一个单独的问题。 - Joseph Silber
跟进问题在这里:https://dev59.com/aXzaa4cB1Zd3GeqPP20t - tptcat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,