【问题标题】:SQLSTATE[42S22]: (SQL: select * from `categories` where `categories`.`departement_id` = 1 and `categories`.`departement_id` is not null)SQLSTATE[42S22]: (SQL: select * from `categories` where `categories`.`departement_id` = 1 and `categories`.`departement_id` is not null)
【发布时间】:2019-05-17 01:56:53
【问题描述】:

我正在尝试选择特定部门的所有类别。

class Test extends Controller
{
    public  function test(){

        $depts=Departement::find(1)->categories;

        foreach ($depts as $dept){
            echo $dept->name;
        }

        return view('test');

    }

}

【问题讨论】:

  • 编辑以提高可读性
  • 错误是什么?为什么要回显数据然后返回视图?您是否将use App\Department; 添加到您的控制器?另外,您确定 ID 为 1 的部门存在吗?
  • 是的部门 ID=1 存在并且使用 App\Department 存在错误是 SQLSTATE[42S22]: (SQL: select * from categories where categories.departement_id = 1 and categories .departement_id 不为空)

标签: laravel-5 orm eloquent


【解决方案1】:

快速的谷歌搜索告诉我 SQLSTATE[42S22] 是“未找到列”的代码。 当您拨打Departement::find(1)->categories 时,Eloquent 会进行 2 次查询

  1. 获取主键等于1的部门
  2. 获取“departement_id”属性等于 1 的所有类别

鉴于您的错误中的查询

select * from `categories` where `categories`.`departement_id` = 1 and `categories`.`departement_id` is not null)

很明显,您的categories 表中没有departement_id 列。

如果您的类别表中没有 departement_id 列

要么:

  • 在迁移中添加它。
  • 如果您不使用迁移,请直接将其添加到数据库中

如果你想让另一列作为外键

更新您的关系方法以反映这一点。

https://laravel.com/docs/5.8/eloquent-relationships

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-27
    • 1970-01-01
    • 2015-10-26
    • 2021-07-25
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多