简体   繁体   English

Laravel Eloquent 查询

[英]Laravel Eloquent Queries

I need help with Eloquent.我需要 Eloquent 方面的帮助。 When i tried searching for manufacturer name it returns nothing, but if i try searching for manufacturer or name , it returns me some results.当我尝试搜索manufacturer name时,它什么也不返回,但如果我尝试搜索manufacturername ,它会返回一些结果。

My current table structure is:我当前的表结构是:

Product:产品:

 manufacturer_id, FK id on manufacturer

 model_id, FK id id on model

Manufacturer:制造商:

 id
 name

Model: Model:

 id
 manufacturer_id, FK id on manufacturer
 name

My code is as such:我的代码是这样的:

    $q = Input::get("query");
    $words = str_replace(" ", "%", $q);

    $cars = Product::whereHas('model', function ($query) use ($words) {
        $query->where('name', 'like', "%$words%");
    })->orWhereHas('manufacturer', function ($query) use ($words) {
        $query->where('name', 'like', "%$words%");
    })->get();

Please help me, I'm really new at this.请帮助我,我真的很陌生。

Try it like this.像这样试试。

$query->where('name', 'like', '%' . $words . '%);

use this.用这个。

$cars = Product::whereHas('model', function ($query) use ($words) {
        $query->where('name', 'like', '%' . $words . '%');
    })->orWhereHas('manufacturer', function ($query) use ($words) {
        $query->where('name', 'like', '%' . $words . '%');
    })->get();

as you're using "%$words%" it'll not take any value.当您使用"%$words%"时,它不会有任何价值。

"%{$words}%" or '%'. $words. '%' "%{$words}%"'%'. $words. '%' '%'. $words. '%' '%'. $words. '%' you can use this as well. '%'. $words. '%'你也可以使用它。

I am not sure why are you doing this:我不知道你为什么这样做:

$words = str_replace(" ", "%", $q);

because later on you are anyway adding "%" with $words variable.因为稍后你无论如何都要用$words变量添加“%”。 So do it like this:所以这样做:

$words = trim(Input::get("query"));

$cars = Product::whereHas('model', function ($query) use ($words) {
    $query->where('name', 'like', "%$words%");
})->orWhereHas('manufacturer', function ($query) use ($words) {
    $query->where('name', 'like', "%$words%");
})->get();

This should work for single words search.这应该适用于单个单词搜索。 Now if you want to match multiple words, seperated by space, you will need to use explode() to actually get each word and write a OR AND WHERE combination to match results.现在如果你想匹配多个单词,用空格分隔,你需要使用explode()来实际获取每个单词并编写一个OR AND WHERE组合来匹配结果。 OR you can use MYSQL FULL TEXT QUERY but that is outside of the scope of this question.或者您可以使用 MYSQL FULL TEXT QUERY 但这不在此问题的 scope 范围内。

Please ask a separate question for that.请为此提出一个单独的问题。

I hope it helps我希望它有帮助

Use concatenation, like this:使用串联,如下所示:

$query->where('name', 'like', '%' . $words . '%);

Instead this:取而代之的是:

$query->where('name', 'like', "%$words%");

Try this one试试这个

$query->Where('column_name', 'LIKE', '%' . $value . '%')

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

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