【问题标题】:How to get the data from model relationship for query builder?如何从查询构建器的模型关系中获取数据?
【发布时间】:2020-10-30 05:15:39
【问题描述】:

我有一个 Product 模型,其中我的 Plan 模型设置了“belongsTo”关系。我通常可以通过{{$product->plan->name}} 来检索刀片文件中某个产品的计划名称。

现在我正在尝试构建一个搜索功能,用户可以在其中搜索与产品相关的产品名称或计划名称。

在我的控制器中,想法是通过查询 Product 模型并查找与用户输入的产品名称相似的产品名称来获取搜索结果。我正在尝试找到一种方法来查找类似于用户输入的计划名称,但我似乎无法正确找到它。

这是我目前正在做的查询:

$results = Product::where('name', 'like', '%', $request->input('search-product-name'), '%')
        ->join('plans', 'products.plan_id', '=', 'plans.id')
        ->orWhere('name', 'like', '%', $request->input('search-product-plan'), '%')->get();

【问题讨论】:

    标签: mysql database laravel eloquent


    【解决方案1】:

    您需要使用whereHas 过滤来自relationship 表的数据假设您已在Product 模型中将plan 设置为relationship 函数,因此您的代码将是这样的

    $results = Product::where('name', 'like', '%'. $request->input('search-product-name'). '%')
        ->whereHas("plan", function ($q) use ($request) {
            $q->where('name', 'like', '%'. $request->input('search-product-plan'). '%');
        })->get();
    

    参考链接https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence

    【讨论】:

    • 我试过这个,这个错误出现在SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'exists (select * from plans` where products.plan_id = plans.plans.id stand...' at line 1 (SQL: select * from products where name like % 存在 (select * from plans where products.plan_id = plans.id standard name like %))`
    • 修复它现在试试
    • 它通过了,但是当我 dd() 它时,它返回 3 个项目,而不仅仅是 1 个。我只填写了 1 个输入字段,即计划名称,它应该返回带有该计划的产品名字而已。这是 dd() 的结果:Illuminate\Database\Eloquent\Collection {#1015 ▼ #items: array:3 [▼ 0 => App\Product {#1054 ▶} 1 => App\Product {#1053 ▶} 2 => App\Product {#1262 ▶} ] }
    • 没关系,我只是用 whereHas 而不是 orWhereHas,非常感谢 Kamlesh!
    猜你喜欢
    • 2017-03-30
    • 1970-01-01
    • 2019-08-31
    • 2023-04-02
    • 2020-04-20
    • 1970-01-01
    • 2021-06-05
    • 2020-06-29
    • 1970-01-01
    相关资源
    最近更新 更多