简体   繁体   English

Laravel Join查询雄辩

[英]Laravel Join query eloquent

I have three models like following: 我有以下三种模型:

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: 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: 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');
}
}

when I run this query I got this error : 当我运行此查询时,出现以下错误:

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

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'fieldID' in 'where clause' (SQL: select * from categories where fieldID = 3) Any help please to know what is the problem !!? SQLSTATE [42S22]:找不到列:1054“ where子句”中的未知列“ fieldID”(SQL:从fieldID = 3的categories中选择*)有任何帮助请知道是什么问题!!?

See Constraining Eager Loads for this purpose: 为此,请参见约束急切负载

$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();

It happends because the where clause is added on the categories table which does not have the fieldID column. 发生这种情况是因为where子句添加在没有fieldID列的类别表上。

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

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