提问者:小点点

在Laravel 5中构建多对多关系的动态查询


我对Laravel雄辩的ORM非常陌生,我很难构建一个动态查询来查询某个类别的产品。

我解析请求对象并根据已传递的变量返回产品。当我查询单个模型时,这很容易,但我想知道如果类别传递到,如何动态构建查询。使用标准MYSQL和PHP很容易做到这一点,但我不确定如何在LAravel中实现这一点。

这是我的密码:

产品型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $primaryKey = 'id',
              $table      = 'products',
              $fillable   = array('title', 'SKU', 'description', 'created_at', 'updated_at');

    public $timestamps = true;

    /**
     * Get the categories assoicated with the product
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     *
     */
    public function categories() {
        return $this->belongsToMany('App\Category')->withTimestamps();
    }
}

类别型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    /**
     * Returns all products related to a category
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function products() {
        return $this->belongsToMany('App\Product')->withTimestamps();
    }

}

在我的产品控制器中,我有这个函数来获取在一个名为“filtervars”的类中调用方法“filterProduct”的产品:

public function index(Request $request)
{
    return FilterVars::filterProduct($request->all());
}

这里是filterProducts方法:

public static function filterProduct($vars) {

        $query = Product::query();

        if((array_key_exists('order_by', $vars)) && (array_key_exists('order', $vars))) {
            $query = $query->orderBy($vars['order_by'], $vars['order']);
        }

        if(array_key_exists('cat', $vars)) {
            $query = $query->whereHas('categories', function($q) use ($vars){
                return $q->where('category_id', $vars['cat']);
            });
        }     

        return $query->get();

产品数据库迁移:

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function(Blueprint $table) {
            $table->increments('id');
            $table->string('title', 75);
            $table->string('SKU')->unique();
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }

以及显示类别表、透视表和外键等结构的迁移:

class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description');
            $table->timestamps();
        });

        Schema::create('category_product', function(Blueprint $table) {
            $table->integer('product_id')->unsigned()->index();
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');

            $table->integer('category_id')->unsigned()->index();
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
            $table->timestamps();
        });
    }

我尝试在查询中加入'have'方法,但这似乎不起作用。有人能告诉我哪里出错了吗?

谢谢


共1个答案

匿名用户

可能你需要where方法

$query = $query->whereHas('categories', function($q) use ($vars) {
    $q->where('id', $vars['cat']);
});

编辑

您应该在whereHas方法中使用id列,因为您将where条件应用于categories表,该表没有category\u id列

public static function filterProduct($vars) {

    $query = Product::query();

    if((array_key_exists('order_by', $vars)) && (array_key_exists('order', $vars))) {
        $query = $query->orderBy($vars['order_by'], $vars['order']);
    }

    if(array_key_exists('cat', $vars)) {
        $query = $query->whereHas('categories', function($q) use ($vars){
            $q->where('id', $vars['cat']);
        });
    }     

    return $query->get();
}