我正在尝试创建具有guest_id和department_to_visit外键的日志条目
SQL:
DROP TABLE IF EXISTS `logs`;
CREATE TABLE `logs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`guest_id` int(11) NOT NULL,
`guest_id_number` int(11) NOT NULL,
`date_time_in` datetime(0) NOT NULL,
`date_time_out` datetime(0) NULL DEFAULT NULL,
`purpose` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`department_to_visit` int(11) NULL DEFAULT NULL,
`updated_at` timestamp(6) NULL DEFAULT NULL,
`created_at` timestamp(6) NULL DEFAULT NULL,
PRIMARY KEY (`id`, `guest_id`) USING BTREE,
INDEX `fk_logs_guests1_idx`(`guest_id`) USING BTREE,
INDEX `fk_logs_dept1_idx`(`department_to_visit`) USING BTREE,
CONSTRAINT `fk_logs_dept1` FOREIGN KEY (`department_to_visit`) REFERENCES `dept` (`dept_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_logs_guests1` FOREIGN KEY (`guest_id`) REFERENCES `guests` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
)
日志模型
class Logs extends Model
{
protected $table = 'logs';
public function guests()
{
return $this->belongsTo('App\Guest','guest_id','id');
}
public function departments()
{
return $this->belongsTo('App\Department','department_to_visit','dept_id');
}
我一直收到错误SQLSTATE [23000]:违反完整性约束:1452无法添加或更新子行:外键约束失败(guest_log
。logs
,CONSTRAINT fk_logs_dept1
外键(department_to_visit
的引用dept
(dept_id
)删除时不采取行动,而对更新不采取行动)(SQL:插入logs
(guest_id
,{{ 1}},guest_id_number
,purpose
,department_to_visit
,date_time_in
,updated_at
)值(4,2,2,1,2018-12-23 12 :53:22,2018-12-23 12:53:22,2018-12-23 12:53:22))
每当我尝试使用创建新的日志记录时
LogController
created_at
使用此方法
public function store(Request $request)
{
$this->validate($request, [
'guest_id'=>'required',
'guest_id_number'=>'required',
'purpose'=>'required',
'department_to_visit']);
$logs = new Logs();
$guest = Guest::findOrFail($request->guest_id);
$logs->guest_id = $guest->id;
$logs->guest_id_number = $request->guest_id_number;
$logs->purpose = $request->purpose;
echo $request->department_to_visit;
$department= Department::findOrFail($request->department_to_visit);
// echo '<pre>',var_dump($department),'</pre>';
$logs->department_to_visit =$department->dept_id;
$logs->date_time_in = Carbon::now();
$logs->save();
// return redirect(route('home'));
}
我以前在guest_id上收到错误,但已解决。我以为guest_id不会有什么不同,但是department_to_visit继续收到错误。请帮助我解决和理解问题的原因
答案 0 :(得分:0)
确实令人费解,因为代码看起来像是在尝试在插入中使用它们之前就立即检索了相关的主键,因此您希望这些事情能够解决。
以下查询之一必须不产生任何行:
SELECT * FROM guests WHERE id = 4
SELECT * FROM dept WHERE dept_id = 1 --is the PK id, or dept_id?
通过提供表中存在的ID来解决此问题。仔细检查您的外键是否引用了正确的远程主键(我注意到来宾表PK被称为ID,而部门表PK似乎被称为dept_id?是否正确?),并且findOrFail方法正在搜索的列肯定是主键柱。 findOrFail有什么可能的方法可以找到某些东西,错误的东西并且不会失败?
最后,当您在查询工具中运行这些数据库时,请绝对确保要在调试中查询的数据库绝对与服务器连接的数据库相同。