繁体   English   中英

Laravel Join查询雄辩

[英]Laravel Join query eloquent

我有以下三种模型:

class Category extends Eloquent
{
protected $primaryKey = 'categoryID';
public $timestamps = false;


protected $fillable = [
    'categoryName',

];

public function categoriesfields()
{
    return $this->hasMany(\App\Models\Categoriesfield::class, 'categoryID');
}
}

Categoriesfield:

class Categoriesfield extends Eloquent
{
protected $primaryKey = 'fieldID';
public $timestamps = false;

protected $casts = [

    'categoryID' => 'int'
];

protected $fillable = [
    'fieldName_ar',
    'categoryID'
];

public function category()
{
    return $this->belongsTo(\App\Models\Category::class, 'categoryID');
}

public function categoriesoptions()
{
    return $this->hasMany(\App\Models\Categoriesoption::class, 'fieldID');
}
}

Categoriesoption:

class Categoriesoption extends Eloquent
{
protected $primaryKey = 'optionID';
public $timestamps = false;

protected $casts = [
    'optionParent' => 'int',
    'fieldID' => 'int'
];

protected $fillable = [
    'fieldID'
];

public function categoriesfield()
{
    return $this->belongsTo(\App\Models\Categoriesfield::class, 'fieldID');
}
}

当我运行此查询时,出现以下错误:

$data= Category::with('category.categoriesfields')-
>with('category.categoriesfields.categoriesoptions')
            ->where('fieldID', '=', 3)->get();

SQLSTATE [42S22]:找不到列:1054“ where子句”中的未知列“ fieldID”(SQL:从fieldID = 3的categories中选择*)有任何帮助请知道是什么问题!!?

为此,请参见约束急切负载

$fieldID = 3; // added the variable here to see how to import it to the closure

$data = Category::with([
    'categoriesfields' => function ($query) use ($fieldID) {
         $query->with('categoriesoptions')->where('fieldID', '=', $fieldID);
    }
])->get();

发生这种情况是因为where子句添加在没有fieldID列的类别表上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM