简体   繁体   English

Laravel 4:选择多对多关系

[英]Laravel 4: selection many to many relation

I work on a blog project, which have relation many to many between "posts" and "cats" tables (with pivote table) 我在一个博客项目上工作,该项目在“职位”表和“猫”表(带有数据透视表)之间有很多关系

posts:
    id
    title
    topic

cats:
    id
    name

cat_post:
    post_id
    cat_id

I prepare models correctly, so, how to select all posts in specific category? 我正确地准备了模型,那么,如何选择特定类别的所有帖子? I tried: 我试过了:

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

and

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

but nothing yet, 但是还没有

This is better/shorter: 更好/更短:

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

Update: 更新:

$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

just found the answer 刚刚找到答案

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

then retrive it in blade: 然后在刀片中检索它:

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

thanks, 谢谢,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM