【问题标题】:Laravel Join query eloquentLaravel Join 查询雄辩
【发布时间】:2017-11-11 01:35:20
【问题描述】:

我有以下三个模型:

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


protected $fillable = [
    'categoryName',

];

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

类别字段:

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

类别选项:

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:select * from categories where fieldID = 3) 任何帮助请知道是什么问题!!?

【问题讨论】:

  • $data= Category::with('category.categoriesfields')->with('category.categoriesfield.categoriesoptions') ->where('fieldID', '=', 3)->得到();试试这个
  • 同样的错误。

标签: php laravel eloquent


【解决方案1】:

为此请参阅Constraining Eager Loads

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

这是因为在没有fieldID 列的类别表上添加了 where 子句。

【讨论】:

  • 我使用了你的解决方案,但我得到了这个:调用模型 [App\Models\Category] ​​上的未定义关系 [category]。
  • 现在检查..你必须删除category.前缀
  • 您是否删除了该类别。关系前缀?
  • 再次更新,请重试
  • 工作,但我也检索到 feildID=4 和 fieldID=5 ??
猜你喜欢
  • 2021-11-09
  • 2018-01-26
  • 2021-07-23
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-11
相关资源
最近更新 更多