donglin317704291 2014-02-22 17:32
浏览 5
已采纳

Laravel 4 Eloquent选择

I have 3 tables

--- Posts (all the posts) rows = id, title, content

--- Boards (all the boards) rows = id, title

--- board_post (the link between boards and posts: many <-> many) rows = board_id, post_id

2 Eloquent classes named board and post

now I would love to select all the posts from a board, based on board_post

I was thinking in the way of: 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

And then how wuld I be able to get all the post opbjects from that?

greetings Glenn

  • 写回答

2条回答 默认 最新

  • duanchen7036 2014-02-22 18:03
    关注

    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).

    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()).


    To do it with your current database setup, use belongsToMany instead:

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行