【问题标题】:Laravel 4 many to many relationshipsLaravel 4 多对多关系
【发布时间】:2014-02-19 12:15:44
【问题描述】:

假设我们必须有以下表格:

游戏

游戏问题

问题

答案

现在为了得到与单人游戏相关的问题,我得到了以下控制器 sn-p:

if ($code) {
            $gamedata = Game::with('questions')
                ->where('secretcode', $code)
                ->get();
        }else{
            $gamedata = Game::with('questions')->get();

        }

这是我的游戏模型:

class Game extends Eloquent {


    /*table definition*/
    protected $table = 'games';


        public function questions(){
        return $this->belongsToMany('Question', 'gamequestions', 'game_id', 'question_id');
    }

}

和问题模型:

class Question extends Eloquent {

/*table definition*/
protected $table = 'questions';

//questions relation
public function answers(){
    return $this->hasMany('Answer', 'question_id', 'id');
}

}

现在获取游戏及其相关问题似乎可以使用此代码。 但我也想包括答案。如何修改此代码以适应另一个外键关系?

【问题讨论】:

    标签: php sql laravel-4 eloquent


    【解决方案1】:

    我相信你可以嵌套关系;

    if ($code) {
                $gamedata = Game::with('questions.answers')
                    ->where('secretcode', $code)
                    ->get();
            }else{
                $gamedata = Game::with('questions.answers')->get();
    
            }
    

    查看文档http://laravel.com/docs/eloquent#eager-loading - 搜索嵌套关系

    $books = Book::with('author.contacts')->get();

    在上面的例子中,作者关系会被预先加载,作者的联系人关系也会被加载。

    【讨论】:

    • 太棒了!谢谢。
    猜你喜欢
    • 2014-07-22
    • 1970-01-01
    • 2013-09-19
    • 2013-09-05
    • 2013-11-14
    • 2018-06-15
    • 2013-05-06
    • 2013-10-21
    • 1970-01-01
    相关资源
    最近更新 更多