(laravel4)从数据透视表中提取数据

时间:2014-06-20 18:56:33

标签: laravel

我试图避免再次提出一个愚蠢的问题,但我在这里......

所以我想检查我的数据透视表(tutorial_id)中的ID是否与另一个ID匹配。但是,我不知道如何从数据透视表中获取此ID ..这是我尝试过的:

控制器:

class TagController extends BaseController {
    public function getTutorials($tag) {
    $tag_id = Tag::where('name', $tag)->first();

    $tutorials = Tutorial::with('tags')->where('tutorial_id', '=', $tag_id->id)->get();
    return View::make('tutorials/tags', array(
        'tutorials' => $tutorials
    ));
}
}

教程模型:

class Tutorial extends Eloquent {
    protected $table = 'tutorials';

    public function tags() {
        return $this->belongsToMany('Tag', 'tutorials_tags', 'tutorial_id');
    }
}

标记模型:

class Tag extends Eloquent {
    protected $table = 'tags';
    public function tutorials() {
        return $this->belongsToMany('Tutorial', 'tutorials_tags', 'tag_id');
    }
}

数据库看起来像这样:

enter image description here 但是我现在得到这个错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tutorial_id' in 'where clause' (SQL: select * from `tutorials` where `tutorial_id` = 1)

1 个答案:

答案 0 :(得分:1)

所以您希望所有教程都使用tag_id->id,您可以这样做:$tag_id->tutorials

我为你重新格式化了代码:

public function getTutorials($tag) {
    $tag = Tag::where('name', $tag)->first();

    return View::make('tutorials/tags', array(
        'tutorials' => $tag->tutorials
    ));
}

参考:http://vegibit.com/many-to-many-relationships-in-laravel/