我将用更多细节来描述这种情况:
我有一个产品列表,每个产品都属于某个类别和某个品牌。有些产品可以得到用户的审查。
在我的Laravel应用程序的/reviews/page上,我有一个评论列表,以及类别和品牌的选择框,当然还有搜索按钮。
若用户并没有选择类别或品牌,所有评论都会被显示、分页,这很好。
当用户选择类别或品牌,或者两者都选择,并试图以这种方式过滤所有评论时,问题就会出现。
Reviews table fields: ID, user_id(foreign key users.ID), product_id(foreign key products.ID), text
Products table fields: ID, category_id(foreign key categories.ID), brand_id(foreign key brands.ID), name
Categories table fields: ID, name
Brands table fields: ID, name
Users table fields: ID, username
当我列出评论时,我只是简单地使用:
$reviews = Review::orderBy('id', 'DESC')->paginate(5);
如果我想按user_id过滤评论,那会很容易,因为评论表包含user_id列,但是,如何根据产品类别和/或产品品牌进行筛选?
以下是评论、产品和类别模型:
<?php namespace App;
use Illuminate'Database'Eloquent'Model;
class Review extends Model {
protected $fillable = [];
public function product() {
return $this->belongsTo('App'Product');
}
public function user() {
return $this->belongsTo('App'User');
}
}
<?php namespace App;
use Illuminate'Database'Eloquent'Model;
class Product extends Model {
protected $fillable = [];
public function user() {
return $this->belongsTo('App'User');
}
public function reviews() {
return $this->hasMany('App'Review');
}
public function category() {
return $this->belongsTo('App'Category');
}
}
<?php namespace App;
use Illuminate'Database'Eloquent'Model;
class Category extends Model {
protected $fillable = [];
public function products() {
return $this->hasMany('App'Product');
}
}
如果我使用联接,那么$review->user->id、$review->user->username、$review->id是不正确的,我在blade模板中得到reviews.product_id为$review->id,products.user_id为$review->user->id。
我正在尝试这个加入变体:
$reviews_query = Review::orderBy('reviews.id', 'DESC')
->Join('products', 'reviews.product_id', '=', 'products.id')
->Join('categories', 'products.category_id', '=', 'categories.id')
->Join('brands', 'products.brand_id', '=', 'brands.id')
->Join('users', 'reviews.user_id', '=', 'users.id')
->where('reviews.active', '=', 1)
->GroupBy('reviews.id')->paginate(5);
这是根据category_id进行过滤的:
if (Input::has('category_id')){
$category_id = Input::get('category_id');
$reviews_query->where('categories.id', $category_id);
}
我不知道如何正确处理刀片模板中不明确的id,如product_id、review_id、user_id($review->id、$review->user->id,所有这些都相互混淆(
在类别模型中添加hasManyThrough关系
public function reviews() {
return $this->hasManyThrough('App'Review', 'App'Product');
}
现在你可以拥有像这样的类别的所有评论
$category->reviews();
您可以向其中添加其他查询子句,如
$category->reviews()->orderBy('id', 'DESC')->paginate(5);
试试这个,
$reviews = DB::table('review')
->join('product', 'product.id', '=', 'review.product_id')
->Join('category', 'product.category_id', '=', 'category.id')
->orderBy('id', 'DESC')->paginate(5);
欲了解更多信息,请访问-Laravel加入3个表
这可能对你有用。。。。。
按特定类别ID过滤所有评论,然后只需使用->
$categoryID = 1;
Categories::with(['products' => function($product){
$product->with('reviews');
}])->where('id', '=', $categoryID)->get();
还通过特定的BrandID过滤所有评论,然后是
$brandID = 1;
Brands::with(['products' => function($product){
$product->with('reviews');
}])->where('id', '=', $brandID)->get();