Laravel关系:使用多个外键查询

时间:2015-02-06 10:21:42

标签: php mysql laravel eloquent

我有以下数据库模式:

    //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();

使用这个Eloquent模型:

 class Pages extends Eloquent {

    protected $table = 'pages';

    public function url()

        {

            return $this->belongsTo('Strings');

        }
}

这不会检索标题,描述和网址的字符串值,而只检索其ID。

我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

这种关系看起来很正确。您唯一需要做的就是加载关系。这里最好的方法是急切加载。它会将db查询减少到最低限度:

$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();