我使用postgresql,我有three table
1:适应训练
code - string(225)
code_menu - string(225)
code_sub_menu - string(225)
name - string(225)2:菜单
code - string(225)
name - string(225)3:子菜单
code - string(225)
name - string(225)我想用雄辩的口才向habilitations展示菜单和子菜单,当我尝试:
Habilitation::with(['menu','submenu'])->get();我知道这个错误:
Illuminate\Database\QueryException
SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: character varying = integer LINE 1: select * from "menu" where "menu"."code" in (0, 0, 0, 0) ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. (SQL: select * from "menu" where "menu"."code" in (0, 0, 0, 0)) 我的模特:
class Menu extends Model
{
protected $table = "menu";
public $primaryKey = "code";
public $timestamps = false;
protected $casts = [
'code' => 'string',
];
public function submenu()
{
return $this->hasMany('App\Models\SubMenu','code');
}
public function habilitation()
{
return $this->hasMany('App\Models\Habilitation','code');
}
}
class SubMenu extends Model
{
protected $table = "submenu";
public $primaryKey = "code";
public $timestamps = false;
protected $casts = [
'code' => 'string',
];
public function menu()
{
return $this->belongsTo('App\Models\SubMenu','code');
}
public function habilitation()
{
return $this->hasMany('App\Models\Habilitation','code');
}
}
class Habilitation extends Model
{
protected $table = "habilitation";
public $primaryKey = "code";
public $timestamps = false;
protected $fillable = [
'code', 'code_menu','code_sub_menu'
];
protected $casts = [
'code' => 'string',
'code_menu' => 'string',
'code_sub_menu' => 'string'
];
public function menu()
{
return $this->belongsTo('App\Models\Menu','code_menu','code');
}
public function submenu()
{
return $this->belongsTo('App\Models\SubMenu');
}
}我没有问题使用laravel的查询生成器,但我想使用雄辩的。有人能帮我吗?还是给我点提示?
先谢谢你
发布于 2020-01-03 08:44:52
我添加了public $keyType = ‘string’;来解决这个问题。提示:https://www.tekmx.com/blog/using-non-standard-primary-key-with-eloquent-relations-laravel-5
发布于 2020-01-03 07:50:12
此错误与PostgreSQL有关。您需要检查正确的类型转换或列数据类型,因为PostgreSQL是严格的,您可以看到类型强制转换为string,但是在查询中它实际上是整数。这通常发生在将INT引用到VARCHAR时,反之亦然。
这
select * from "menu" where "menu"."code" in (0, 0, 0, 0)实际上应该是
select * from "menu" where "menu"."code" in ('0', '0', '0', '0')因此,我建议将字符串数据类型更改为int,以获取主键和外键。
发布于 2020-10-21 02:02:44
我在使用Postgres和MorphMany关系时也遇到了同样的问题。我通过在返回关系的模型中将keyType设置为string来解决这个问题,我没有将它直接设置为模型,因为我希望将keyType设置为integer。
public function merchantOrderable(): MorphMany
{
$morph = $this->morphMany(OrderModel::class, 'merchant_orderable');
$morph->getParent()->setKeyType('string');
return $morph;
}https://stackoverflow.com/questions/59574496
复制相似问题