【发布时间】:2016-10-06 00:35:39
【问题描述】:
我对 Laravel Eloquent 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());
}
这里是 filterProduct 方法:
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();
});
}
我曾尝试在查询中加入“has”方法,但这似乎不起作用。谁能告诉我哪里出错了?
谢谢!
【问题讨论】: