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

时间:2017-11-16 10:57:08

标签: php mysql laravel

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

Product.php:

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

Category.php:

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

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

我尝试过这样的事情:

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();
}

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

3 个答案:

答案 0 :(得分:0)

就像是

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)


}

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

@page "/foods/create"
@inject HttpClient http
@inject NavigationManager uriHelper
<h3>Create</h3>
<Form ButtonText="Create Foods" foodGrp="@dev1" foods="@dev" 
      OnValidSubmit="@CreateFoods" />
@code {
    Foods dev = new Foods();
    FoodGroups[] dev1 { set; get; }

    protected override async Task OnInitializedAsync()
    {
        dev1 = await http.GetFromJsonAsync<FoodGroups[]>("api/foodgroups");
    }

    async Task CreateFoods()
    {
        await http.PostAsJsonAsync("api/foods", dev);
        uriHelper.NavigateTo("foods");
    }

}

public function getAllData()
{
    $data = tableName::where('Method','Delivery')->get();
    return response()->json($data, 200);
}