关联或保存关系仅在Laravel中为空时有效 [英] Associate or save relationship only works when nullable in Laravel

查看:20
本文介绍了关联或保存关系仅在Laravel中为空时有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到在laravel中关联或保存模型时的解释仅在将外键设置为可为空时才起作用,否则给我违反完整性约束的条件:1452.我假定使外键为a时使它为空不好的做法,多数情况下是如果我必须处理一对多的关系.

I can't find where is the explanation when associate or save a model in laravel only works when the foreign key is set to nullable, otherwise gives me Integrity constraint violation: 1452. I assume that make a foreign key null its a bad practice, most if i have to working with one to many relationships.

示例

$lugarCompra = Input::get('lugar_compra');
$lugarCompra = Lugares_compra::find($lugarCompra);

$tipoPago    = Input::get('tipo_pago');
$tipoPago    = Tipos_pago::find($tipoPago);

$origen      = Input::get('origen');

$fecha_embarque = Input::get('fecha_embarque');
$fecha_embarque = date("Y-m-d", strtotime($fecha_embarque));

$hora_embarque  = Input::get('hora_embarque');

$ordenDeCompra = Ordenes_compra::create(array(
                        'lugar_origen' => $origen,
                        'fecha_embarque' => $fecha_embarque,
                        'hora_embarque' => $hora_embarque,
));

$ordenDeCompra->save();

// THIS NOT WORKING, GIVES ME INTEGRITY CONSTRAINT VIOLATION.
$ordenDeCompra = $lugarCompra->ordenesCompra()->save($ordenDeCompra);
$ordenDeCompra = $tipoPago->ordenesCompra()->save($ordenDeCompra);

// THIS ALSO NOT WORKS, GIVES ME INTEGRITY CONSTRAINT...
$ordenDeCompra->lugar_compra()->associate($lugarCompra)->save();
$ordenDeCompra->tipo_pago()->associate($formaPago)->save();

是的,父表具有数据,所以这不是问题.仅在外键为nullable()的情况下有效,做到这一点的最佳方法是什么?在我看来,Nullable似乎是一个hack ...Tnx的答复...

And yes, the parent tables has data so thats not the problem. Only works if the foreign key is nullable(), what is the best way to do this?? Nullable seems a hack to me... Tnx for the replies...

推荐答案

在这种情况下,我不认为使外键可为空不是一种破解,但是这取决于您的数据.

I don't think that making the foreign key nullable is a hack in this situation, but it would depend on your data.

在我的项目中,我有一个模型 User 和一个模型 Client .一个 User 可能是最多一个 Client 的管理员,但他们也可以是不是管理员的普通用户.这是一对多的关系,因此我向用户表添加了一个client_id外键.

In my project, I have a model User and a model Client. A User may be an administrator for at most one Client, but they could also be a regular user, who is not an administrator. This is a one-to-many relationship, so I add a client_id foreign key to the users table.

client_id并不总是设置的,并且对于大多数用户而言实际上为null.

The client_id is not always set, and is actually null for the majority of users.

我认为这与您的情况类似(由于您的代码中的语言,我无法确切说出).如果您表示的是可选一对多关系,那么可为空的外键是完全可以接受的表示形式.

I think this is similar to your situation (I can't tell exactly because of the language in your code). If you are representing an optional, one-to-many relationship, then a nullable foreign key is a perfectly acceptable representation.

这篇关于关联或保存关系仅在Laravel中为空时有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆