简体   繁体   English

Laravel 雄辩的“with”和“where”多表

[英]Laravel eloquent "with" and "where" with multiple tables

I've 3 tables on my project:我的项目中有 3 个表:

  1. Mall购物中心
  2. Shop店铺
  3. Product产品

I've a page to search for products in the whole database.我有一个页面可以在整个数据库中搜索产品。 I need an option where they can search the product by the mall name.我需要一个选项,他们可以通过商场名称搜索产品。 So I built my code like this:所以我像这样构建了我的代码:

$query = Product::with('shop', 'shop.mall');

if (!empty($data["keyword"])) {
    $query = $query->where(function($q) use($data) {
         $q->where('shop.mall.name', 'LIKE', '%' . $data["keyword"] . '%')->orWhere('shop.mall.keyword', 'LIKE', '%' . $data["keyword"] . '%');
    });
}

But it is showing this error:但它显示此错误:

Column not found: 1054 Unknown column 'shop.mall.name' in 'where clause'

Is there any problem with my query?我的查询有问题吗? Thank you谢谢

To search within relation use whereHas(), it creates subquery and returns data filtered in shop.mall. 要使用whereHas()在关系中进行搜索,它将创建子查询并返回在shop.mall中过滤的数据。

    $query = Product::with('shop', 'shop.mall');

    if (!empty($data["keyword"])) {
        $query = $query->whereHas('shop.mall',function($q) uses ($data){
            $q->where('name', 'LIKE', '%' . $data["keyword"] . '%')->
              orWhere('keyword', 'LIKE', '%' . $data["keyword"] . '%');
        });
    }

I have two tables linked one to many (files -> people).我有两个表一对多(文件-> 人)。 I need to select all files where people have a certain name but i need the whole group of that selection.我需要选择人们具有特定名称的所有文件,但我需要该选择的整个组。

FILES: id numero anno 1 1 2020 2 1 2021文件:id numero anno 1 1 2020 2 1 2021

PEOPLE: id fascicoli_id fascicoli_numero fascicoli_anno cognome 1 1 1 2020 Urbano 2 1 1 2020 Del Mastro 3 2 2 2021 Di Ciano人:id fascicoli_id fascicoli_numero fascicoli_anno cognome 1 1 1 2020 Urbano 2 1 1 2020 Del Mastro 3 2 2 2021 Di Ciano

Well, if I do a search where 'cognome' LIKE '% Del' (id = 2), I must also receive the other records with the same fascicoli_id (therefore 'Del Mastro' and 'Urbano').好吧,如果我在 'cognome' LIKE '% Del' (id = 2) 的地方进行搜索,我还必须接收具有相同 fascicoli_id 的其他记录(因此是 'Del Mastro' 和 'Urbano')。

I have tried with the following (where $ query is the search parameter I pass with GET method in ajax):我尝试了以下操作(其中 $ query 是我在 ajax 中使用 GET 方法传递的搜索参数):

$ fascicoli = Fascicoli :: with ('person') -> get ();
$ fascicoli = $ fascicoli [0] -> person () -> where ('surname', 'like', '%'. $ query. '%') -> get ();

and also:并且:

$ fascicoli = Fascicoli :: whereHas ('person', function ($ sub) use ($ query) {
    $ sub-> where ('last name', 'like', '%'. $ query. '%')
}) -> get ();

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

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