【问题标题】:Laravel 4: selection many to many relationLaravel 4:选择多对多关系
【发布时间】:2014-07-22 07:25:54
【问题描述】:

我从事一个博客项目,该项目在“posts”和“cats”表(带有数据透视表)之间存在多对多的关系

posts:
    id
    title
    topic

cats:
    id
    name

cat_post:
    post_id
    cat_id

我正确地准备了模型, 那么,如何选择特定类别的所有帖子?我试过了:

Cat::with('post')->where('id', '=', '3')->get();

Post::with('cat')->whereId('3')->get();

但还没有,

【问题讨论】:

    标签: php laravel laravel-4 many-to-many


    【解决方案1】:

    这样更好/更短:

    $cats = Cat::with('post')->find(3);
    

    更新:

    $cats = Cat::with(array('post' => function($q) { // make sure posts not post
        $q->orderBy('id', 'desc'); // order the posts
    }))->find(3); // No need to order a single model
    

    【讨论】:

    • 更新了答案。欢迎:-)
    【解决方案2】:

    刚刚找到答案

    $cats = Cat::with('post')->whereId(3)->first();
    

    然后在刀片中检索它:

    @foreach($cats->post as $post)
        {{$post->title}}
    @endforeach
    

    谢谢,

    【讨论】:

    • 检查我的答案,它更短。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 2017-09-26
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 2013-09-05
    相关资源
    最近更新 更多