Laravel关系:与多个外键
问题描述:
查询我有以下DB模式:Laravel关系:与多个外键
//Pages schema
Schema::create('pages', function($table)
{
$table->increments('id');
$table->softDeletes();
$table->timestamps();
$table->integer('parent_id');
$table->integer('ordination');
$table->unsignedInteger('title_id'); //Refer to strings
$table->unsignedInteger('description_id'); //Refer to strings
$table->unsignedInteger('url_id'); //Refer to strings
//Foreign key
$table->foreign('title_id')->references('id')->on('strings');
$table->foreign('description_id')->references('id')->on('strings');
$table->foreign('url_id')->references('id')->on('strings');
});
//Strings
Schema::create('strings', function($table)
{
$table->increments('id');
$table->softDeletes();
$table->timestamps();
$table->text('en');
$table->text('de');
});
我怎么能检索对应的URL字符串页面对象?
我想有一个页面对象或数组类似如下:
$page['url']['en'] = 'about'
$page['title']['en']= 'About title'
$page['description']['en']= 'About description'
etc..
我可以检索从相关网址的页面对象执行以下雄辩查询:
$page= Pages::whereHas('url', function($url)
{
$url->where('en', '=', 'About');
})->first();
有了这个雄辩模型:
class Pages extends Eloquent {
protected $table = 'pages';
public function url()
{
return $this->belongsTo('Strings');
}
}
这不会检索字符串值的标题,描述和d网址,但只有他们的ID。
我该怎么做?
答
该关系看起来正确。你唯一需要做的就是加载关系。这里最好的办法是急切的加载。它将数据库查询减少到最低:
$pages = Page::with('url')->get();
$page = Page::with('url')->find(1);
$page = Pages::with('url')->whereHas('url', function($url){
$url->where('en', '=', 'About');
})->first();
要贪婪加载所有字符串的关系简单地将它们添加到with()
电话:
$pages = Page::with('url', 'title', 'description')->get();
谢谢您的回答,这个解决方案工作正常! – Spetty 2015-02-06 11:34:05