简体   繁体   English

Laravel 4 Eloquent选择

[英]Laravel 4 Eloquent select

I have 3 tables 我有3张桌子

--- Posts (all the posts) rows = id, title, content ---帖子(所有帖子)行= id,标题,内容

--- Boards (all the boards) rows = id, title ---板(所有板)行= id,标题

--- board_post (the link between boards and posts: many <-> many) rows = board_id, post_id --- board_post(板和帖子之间的链接:很多< - >很多)rows = board_id,post_id

2 Eloquent classes named board and post 2个雄辩的课程,名为board and post

now I would love to select all the posts from a board, based on board_post 现在我想根据board_post选择一块板上的所有帖子

I was thinking in the way of: Posts::whereIn('id', $board->post_ids()) 我想的方式是: Posts::whereIn('id', $board->post_ids())

how would I be able to do this, that first off that if I do Board::find(1)->post_ids I get all the post id's of that board 我怎么能做到这一点,首先,如果我做Board :: find(1) - > post_ids我得到该板的所有帖子ID

And then how wuld I be able to get all the post opbjects from that? 那么我怎么能从中得到所有的后期对象呢?

greetings Glenn 问候格伦

In Board model make sure you define belongsToMany relationship 在Board模型中,确保定义belongsToMany关系

public function posts()
{
    return $this->belongsToMany('Post', 'board_post');
}

Now you should be able to do this: 现在你应该能够做到这一点:

Board::find({id})->posts

Forther reading material: http://laravel.com/docs/eloquent#relationships 其他阅读材料: http ://laravel.com/docs/eloquent#relationships

Why are you using a many-to-many relationship for Posts and Boards? 你为什么要使用帖子和板子的多对多关系? It would most likely be a one-to-many relationship: A Board may have several posts, but a Post should only belong to one board (this would simplify your database structure to remove the board_post table). 它很可能是一对多关系:一个董事会可能有几个帖子,但一个帖子应该只属于一个董事会(这将简化你的数据库结构以删除board_post表)。

You would then do: 然后你会这样做:

Inside of Board class: 董事会课程内部:

public function posts() {
  return $this->hasMany('Post', 'board_id');
} 

Then, Board::find(1)->posts would get you all of the posts for that board (use posts, not posts()). 然后,Board :: find(1) - >帖子将获得该板的所有帖子(使用帖子,而不是帖子())。


To do it with your current database setup, use belongsToMany instead: 要使用当前的数据库设置,请使用belongsToMany:

public function posts() {
  return $this->belongsToMany('Post', 'board_post');
} 

If you want to load a Board WITH all of it's posts (eager-loading) use this: 如果你想加载一个董事会所有的帖子(急切加载)使用这个:

Board::with('posts')->find(1)

Otherwise, just to get the posts for a particular board, use: 否则,只需获取特定电路板的帖子,请使用:

Board::find(1)->posts

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

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