【问题标题】:How to select all records with relation and where clause Laravel MySQL如何使用关系和 where 子句 Laravel MySQL 选择所有记录
【发布时间】:2023-04-01 02:43:01
【问题描述】:

我是 Laravel 的新手,所以我遇到了一些问题。我的数据库中有“类别”和“产品”表。在我的模型中,我设置了如下关系:

Product.php:

public function category() 
{
    return $this->belongsToMany(Category::class);
}

Category.php:

public function products() 
{
    return $this->hasMany(Product::class);
}

我现在需要的是选择所有类别及其相关产品。 (用户在搜索栏中输入类别名称并获取类别列表,当用户选择类别时,我会从类别中获取所有列以及与该类别相关的产品)。

我尝试过这样的事情:

public function findCategory(Request $request)
{
    return Category::with('products')
        ->where('name', 'like', '%' . $request->category_name . '%')
        ->limit(15)
        ->get();
}

还有:

public function findCategory(Request $request)
{
    return Category::where('name', 'like', '%' . $request->category_name . '%')
        ->products()
        ->limit(15)
        ->get();
}

但这似乎不起作用,我的想法也用完了。有谁知道是否有办法做到这一点?任何帮助将不胜感激:)

【问题讨论】:

  • 在产品集合中您是从哪里搜索还是从类别搜索?
  • 不确定我是否理解您的问题。但我不需要产品集合中的“位置”。 where 子句应该在类别上。基本上像 Category::where('name', 'like', '%' . $request->category_name . '%') 这工作得很好,但我也想获得与特定类别相关的产品
  • 是否存在多对多关系?
  • 是的,现在我得到了我的 vue 组件数据 - 类别列表(其中我有 id、name 等列),我还想要一个与这个特定类别相关的产品数组
  • 看到这个希望对你有帮助 -> link

标签: php mysql laravel


【解决方案1】:

应该是这样的

public function findCategory(Request $request)
{

    $term = $request->category_name;

    return Category::with('products')->where(function($q) use($term) {
               $q->where('categories.name','like',"%$term%");
            })->paginate(15); //or use limit(15)


}

【讨论】:

  • 哦,但是等等,where 子句不是搜索关系吗? (在哪里执行产品而不是类别?)原因,不幸的是,它似乎不起作用。我正在使用 axios 来获取结果(在我的 vuejs 组件中),但它只是响应“未捕获(承诺中)错误:请求失败,状态码 500”:(
  • 哦,对不起。打错了。现在检查。
【解决方案2】:

您的查询几乎完成,只是您没有加载相关模型。因此,你的最后一个例子应该是:

public function findCategory(Request $request)
{
    return Category::where('name', 'like', '%' . $request->category_name . '%')->
      ->with('products') //load related products
      ->limit(15)
      ->get();
}

【讨论】:

  • 我想我已经尝试过了,但没有成功,所以我认为我的模型中一定有某种错误
  • hmm 使用条件运行查询,看看是否仍然得到任何结果
【解决方案3】:
public function getAllData()
{
    $data = tableName::where('Method','Delivery')->get();
    return response()->json($data, 200);
}

$users = DB::table_Name('users')->select('name', 'email as user_email')->get();

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
猜你喜欢
  • 2016-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-31
  • 2013-10-25
  • 2018-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多