简体   繁体   English

如何选择所有具有关系和 where 子句 Laravel MySQL 的记录

[英]How to select all records with relation and where clause Laravel MySQL

I'm new to Laravel so I have a bit of a problem.我是 Laravel 的新手,所以我有一点问题。 I have tables 'Categories' and 'Products' in my DB.我的数据库中有“类别”和“产品”表。 In my models I setup the relations like:在我的模型中,我设置了如下关系:

Product.php:产品.php:

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

Category.php:类别.php:

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

What I need now is that I want to select all of the Categories with their related Products.我现在需要的是选择所有类别及其相关产品。 (User enters in search bar category name and gets list of Categories and when user selects Category I get all of the columns from Categories and ALSO Products related with this Category). (用户在搜索栏类别名称中输入并获取类别列表,当用户选择类别时,我会从类别和与此类别相关的产品中获取所有列)。

I have tried something like this:我试过这样的事情:

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

ALSO:还有:

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

But this doesn't seem to work and I ran out of ideas.但这似乎行不通,我的想法用完了。 Does anyone know if there is a way to do this?有谁知道是否有办法做到这一点? Any help would be much appreciated :)任何帮助将不胜感激:)

it would be something like它会是这样的

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)


}

Your query is almost complete except that you didn't load related model.除了您没有加载相关模型之外,您的查询几乎完成。 Therefore, you last example should be:因此,您的最后一个示例应该是:

public function findCategory(Request $request)
{
    return Category::where('name', 'like', '%' . $request->category_name . '%')->
      ->with('products') //load related products
      ->limit(15)
      ->get();
}
public function getAllData()
{
    $data = tableName::where('Method','Delivery')->get();
    return response()->json($data, 200);
}

OR要么

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

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

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