【问题标题】:Laravel 4 and Eloquent: retrieving all records and all related recordsLaravel 4 和 Eloquent:检索所有记录和所有相关记录
【发布时间】:2014-03-11 04:42:44
【问题描述】:

我有两个班级:ArtistInstrument。每个Artist 可以播放一个或多个Instruments。并且每个Instrument 可以分配给一个或多个Artists。所以,我设置了以下类:

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


我能够成功地检索到 one 艺术家及其相关乐器,如下所示:

ArtistController.php

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

我有 3 个问题:

  1. 在我看来,我可以像这样输出$artist

    {{ $artist->firstname }}
    

    我可以遍历$instruments,例如:

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

    但是是否可以迭代 $artist(我知道只有一个 - 请参阅 #2)并且对于每个 $artist 迭代它们的 $instruments

  2. 在我的控制器中,我将如何让 所有 艺术家以及每个艺术家与他们关联的乐器在我的视图中迭代它们的最终目标,如 #1 中所述。 p>

  3. 是否可以只检索上述ArtistController.php 示例中的特定列?我试过这个:

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

    但我收到一条错误消息,提示 Collection::instruments() 未定义。

我假设我的模特关系中有什么不对劲的地方。我还尝试用hasMany 定义我在 Artist.php 中的关系(我认为说“每个艺术家都有很多乐器”更有意义,但这给了我一个错误,因为它期待一个名为artists_instruments 的表,它还试图检索该表中不存在的列(如name)。

【问题讨论】:

  • 尝试在 ->get('firstname') 中包含 Artist 的关系密钥。 (我假设它会是这样的 'id':->get('id', 'firstname'))

标签: orm laravel foreign-key-relationship eloquent


【解决方案1】:

你的模特关系很好。

控制器:

$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

【讨论】:

  • 我只是偶然发现了您发布的答案,而这正是我所做的。谢谢!
  • 还有一件事(如果有意义,我可以将其作为一个单独的问题发布)如果我不想检索所有列,我将如何指定要检索的列?我尝试在各个地方使用select(),但似乎没有任何效果。
  • @tptcat - 这绝对应该是一个单独的问题。
猜你喜欢
  • 2016-02-18
  • 2019-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多