【发布时间】:2014-05-28 19:27:41
【问题描述】:
我整天都在解决急切加载/n+1 问题,研究、阅读和观看了有关此问题的教程,但尚未解决。我已经为模型设置了关系,但是当我使用辅助函数传入数据时,我遇到了这个 n+1 问题。 我想从 url site.com/Artist/songs 中获取一个艺术家的名字并获取它的所有歌曲并显示一个这样的 url。
site.com/$Artist/songs/$id
我的艺术家/index.blade.php 视图看起来像这样http://i61.tinypic.com/2nqzatk.jpg 我不确定我在这里缺少什么。
提前致谢!
我的桌子
歌曲 id、标题、正文、slug、点击数、artist_id、created_at、updated_at
艺术家 id, name, body, created_at, updated_at
routes.php
Event::listen('illuminate.query', function($query)
{
var_dump($query);
});
...
Route::get('{artist}/songs', 'ArtistsController@index');
Route::get('{artist}/songs/{id}', ['as' => 'artist.songs.show', 'uses' => 'ArtistsController@show']);
型号:Song.php
class Song extends Eloquent {
protected $guarded = ['id'];
/**
* Setting up relationship for the artist model for easier usage
*
*/
public function artist()
{
return $this->belongsTo('Artist');
}
// Override find method
public static function find($id, $name = null)
{
$song = static::with('artist')->find($id);
// If the song is found
if ($song)
{
// If the song doesn't belong to that artist, throw an exception which will redirect to home, defined in global.php
if ($name and $song->artist->name !== $name)
{
throw new Illuminate\Database\Eloquent\ModelNotFoundException;
}
return $song;
}
// If the song is not found, throw an exception which will redirect to home, defined in global.php
else
{
throw new Illuminate\Database\Eloquent\ModelNotFoundException;
}
}
// Get songs from artist
public static function byArtist($name)
{
return Artist::byName($name)->songs;
}
}
模型艺术家.php
class Artist extends Eloquent {
protected $fillable = [];
/**
* Setting up relationship with the song model for easier usage
* $artist->songs;
*/
public function songs()
{
return $this->hasMany('Song');
}
// Get artist by name
public static function byName($name)
{
return static::whereName($name)->first();
}
}
控制器:ArtistsController.php
class ArtistsController extends BaseController {
// Set default layout for this controller
protected $layout = 'layouts.master';
/**
* Display a listing of the resource.
* GET /artists
*
* @return Response
*/
public function index($name)
{
$this->data['songs'] = Song::byArtist($name);
$this->layout->content = View::make('artists.index', $this->data);
}
helpers.php
function link_to_artist_song(Song $song)
{
return link_to_route('artist.songs.show', $song->title, [$song->artist->name, $song->id]);
}
艺术家的索引视图 艺术家/index.blade.php http://i61.tinypic.com/2nqzatk.jpg
@extends('layouts.master')
@section('content')
@if(isset($songs))
<h1>All Songs</h1>
<ul class="list-group">
@foreach($songs as $song)
<li class="list-group-item">{{ link_to_artist_song($song) }}</li>
@endforeach
</ul>
@endif
@stop
【问题讨论】:
标签: php laravel eager-loading