【问题标题】:laravel orm : where condition on table -> related table -> related tablelaravel orm :表上的条件 -> 相关表 -> 相关表
【发布时间】:2017-03-11 06:58:11
【问题描述】:

这是我的书店数据库

books : id ,title 
category : id,  title 

book_category : id , book_id,  category_id 
book_stock : id , book_id , quantity , price 

考虑到模型中定义了所有关系,我可以查询book_stock 它是这样的

Stock::with('Book')->get();

但是如果我想在category = 1 中获得book 中的stock 怎么办

我可以在书上使用使用条件

Stock::with('Book' , function($q){
   $q->where(['title'=>'abc']);
})->get();

但是我如何过滤相关的书表? 基本上我想从book_category 那里得到book_id category_id = 1 然后使用这些ID 过滤我的books 最后得到stock

ps:我不想使用查询生成器

【问题讨论】:

  • ...with('Book.stock', function($q){...}
  • @Andrew 我没有看到对book_category 的任何引用?
  • 根据需要添加,with 随心所欲。 with('Book.stock', 'Book.category').
  • 是的,应该可以正常工作。从技术上讲。
  • @Andrew thanx ,将其发布为答案,以便我选择它作为正确答案

标签: php laravel laravel-5.2


【解决方案1】:

这将返回属于 category=1 的所有书籍及其库存信息:

$categoryId = 1;

$books = Book::with('stock')->whereHas('category', function($query) use ($categoryId) {
    return $query->where('id', $categoryId);
})->get();

【讨论】:

    【解决方案2】:

    你可以这样做:

    Stock::with('Book.stock', 'Book.category')->get();
    

    您可以在with 语句中访问任意数量的嵌套关系。


    相关问题:

    Laravel nested relationships


    Armin Sam 的回答也应该是一个可行的选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      相关资源
      最近更新 更多