【问题标题】:Laravel 8 getting SQL error in eloquent query while getting nested JSON response of two related TableLaravel 8 在 eloquent 查询中获取 SQL 错误,同时获取两个相关表的嵌套 JSON 响应
【发布时间】:2021-06-28 05:48:44
【问题描述】:

我遇到 SQL 错误,模型名称正在连接两个表,列名称正在返回 'i_t_e_m__l_o_c__m_d_l_LOC_ID' 而不是 'LOC_ID'

Illuminate\Database\QueryException: SQLSTATE[42S22]: 
[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'i_t_e_m__l_o_c__m_d_l_LOC_ID'. 
(SQL: select * from [tblDepartment] where [tblDepartment].[i_t_e_m__l_o_c__m_d_l_LOC_ID] in (1, 2))

这是我的模型代码

    protected $primarykey = 'LOC_ID';
    protected $connection = 'sqlsrv';
    protected $table = 'tblLocation';
   
    public function departments()
    { 
        return $this->hasMany(departmentsModel::class);
    }

这是给控制器的

    public function allLoc(Request $request){
    $data = locationModel::with('departments')->get();
    return response()->json($data);

【问题讨论】:

标签: json eloquent laravel-8


【解决方案1】:

在关系函数中定义外键

public function departments()
{ 
    return $this->hasMany(Comment::class, 'foreign_key', 'local_key');
}

更多详情请查看:laravel.com/docs/8.x/eloquent-relationships#one-to-many

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-30
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多