我有3个表,我希望能够获取功能value_number
为2
且字段show_list
为1
Products
|------|
| id |
|------|
| 1 |
Features
|------|--------------|-------------|
| id | value_num | field_id |
|------|--------------|-------------|
| 1 | 2 | 1 |
|------|--------------|-------------|
| 2 | 3 | 2 |
Fields
|------|---------------|
| id | show_list |
|------|---------------|
| 1 | 1 |
|------|---------------|
| 2 | 0 |
我的模特看起来像:
产品
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
public function features()
{
return $this->belongsToMany(Feature::class);
}
}
特性
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Feature extends Model
{
public function products()
{
return $this->belongsToMany(Products::class);
}
public function field()
{
return $this->belongsTo(Field::class);
}
}
字段
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Field extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
public function features()
{
return $this->hasMany(Feature::class);
}
}
我的查询得到的最远的是:
$category = $category->load(['products' => function ($query) {
$query->with(['features' => function ($query) {
$query->join('fields', 'features.field_id', '=', 'fields.id')
->with('field')
->where('show_list', 1)
->where('value_number', 2);
}]);
}]);
以下有效,但查询很可怕,我确信必须有更好的方法:
$category = $category->load(['products' => function ($query) {
$query->with(['features' => function ($x) {
$x->with('field')
->whereHas('field', function($y) {
$y->where('show_list', 1);
});
}])
->whereHas('features', function ($query) {
$query->where('value_number', 2);
});}]);