【问题标题】:Integrity constraint violation: 1052 Column 'created_at' in where clause is ambiguous in laravel完整性约束违规:1052 列'created_at' in where 子句在 laravel 中不明确
【发布时间】:2020-11-23 05:16:23
【问题描述】:

我的控制器代码是

$data = DB::table('ride')
                    ->leftJoin('driver','ride.driver_id','=','driver.id')
                    ->select([
                    DB::raw('driver.name as driver_name'),
                    DB::raw('monthname(ride.created_at) as month'),
                    DB::raw('year(ride.created_at) as year'),
                ])
                ->where("driver.users_id", $users_id)
                ->groupBy(['year', 'month','driver_id'])
                ->get()
                ->toArray();

但它显示违反完整性约束:1052 列“created_at”在 where 子句中是不明确的,尽管我已经提到了“ride.created_at”

型号

protected $table = "ride";

public $timestamps = false;

protected $fillable =[
        'status',
        'driver_id',

];

【问题讨论】:

  • 您的骑行模型是什么样的?你能展示它的迁移吗?
  • 检查更新的问题
  • @afra-janjua 我认为显示迁移文件而不是模型会更好。
  • 好的,我添加了迁移和模型

标签: laravel


【解决方案1】:

我认为这不应该包含在您的“骑行”模型中。

公共 $timestamps = false;

【讨论】:

    【解决方案2】:

    我刚刚设置了新项目来测试它。 没有关于driver表的说明,只是添加了可以推断的内容。
    在我的环境中(laravel7 + mysql),它只是抱怨driver.name 不在组中。 将driver_name字段添加到分组依据后,它就可以工作了。

    我认为不是上面查询的问题。或者您错过了问题中的某些内容。

    因为你没有在where 子句中使用created_at

    • ride迁移
    $table->increments('id');
    $table->integer('driver_id')->unsigned();
    $table->foreign('driver_id')->references('id')->on('driver');
    $table->timestamps();
    
    • driver迁移
    $table->increments('id');
    $table->string('name');
    $table->integer('users_id');
    $table->timestamps();
    
    • 直接调用web路由
    Route::get('/', function () {
        $users_id = 1;
    
        $data = DB::table('ride')
            ->leftJoin('driver', 'ride.driver_id', '=', 'driver.id')
            ->select([
                DB::raw('driver.name as driver_name'),
                DB::raw('monthname(ride.created_at) as month'),
                DB::raw('year(ride.created_at) as year'),
            ])
            ->where("driver.users_id", $users_id)
            ->groupBy(['year', 'month', 'driver_id', 'driver_name'])
            ->get()
            ->toArray();
    
        dd($data);
    });
    

    【讨论】:

      猜你喜欢
      • 2020-10-13
      • 2019-04-14
      • 2022-11-24
      • 2013-10-16
      • 2019-02-22
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多