duanmi1900 2015-10-08 11:10
浏览 66
已采纳

CakePHP 3,$ this-> Element-> save($ element)无理由地返回false(没有验证错误或缓存问题)

I'm stuck with my CakePHP project because in my controller, save() is returning false (if I leave a field blank) even though there are no validation problems.

I created from scratch a new simplified project to reproduce the issue (and the problem actually it's still there:

This is the database:

CREATE TABLE cars ( 
    id INT UNSIGNED AUTO_INCREMENT NOT NULL,
    make VARCHAR(50) NOT NULL,
    model VARCHAR(50) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE images ( 
    id INT UNSIGNED AUTO_INCREMENT NOT NULL,
    car_id INT UNSIGNED,
    PRIMARY KEY (id),
    FOREIGN KEY car_key (car_id) REFERENCES cars (id)
);

The 'images' table only contains the id and a reference to the cars table since the image will be then stored with the id as the filename.

Then, I did nothing else that let CakePHP generate the useful stuff:

bin/cake bake all --everything

I started the server and created a couple of 'cars', then if I try to add an 'image' that works only if I select a car in the dropdown, if I leave that field blank save() will return false (even though there are no validation constraints on that field).

(In the complete version, the form has the possibility to add an image file, that will be saved with the element id as the filename, that part works well).

If I create an image (selecting a car), then I go to Edit, I'm able to remove the reference to Cars, it is saved correctly.

Why that happens?

EDIT:

Could that be a bug in CakePHP, when you have just an id and a foreign key field? If I add a third column to the 'images' table (name VARCHAR(50)), and regenerate the project, then I'm allowed to create an 'image' without referencing a 'car', even though I leave all the fields blank.

EDIT 2:

Tried logging all the queries in mysql:

If, in the form, I select a 'car_id' then the query is ran:

INSERT INTO images (car_id) VALUES (5)

If i don't select a 'car_id' no query is attempted. If I try to run the correct query manually, it works:

INSERT INTO images () VALUES ()
  • 写回答

2条回答 默认 最新

  • doz22551 2015-10-08 14:15
    关注

    if I try to add an 'image' that works only if I select a car in the dropdown

    Your table constraints prevent you from creating a record without specifying value for foreign key field car_id (You will see the failing query if you check query log using DebugKit).

    Set default value for field car_id to NULL if you want to be able to create a record without providing a valid foreign key value for id.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划