尝试与其他字段以一对多关系插入数据失败

时间:2018-08-24 15:35:25

标签: laravel eloquent laravel-5.2

我正在尝试通过父级关系创建记录。

我的模特

use Illuminate\Database\Eloquent\Model;

class Cheque extends Model
{
    protected $fillable = [
        "numero",
        "banco",
        "factura_id",
    ];

    public function factura()
    {
        return $this->belongsTo('App\Factura');
    }
}

class Factura extends Model
{
    protected $fillable = [
        'cliente_id',
        'cotizacion_id',
        'sub_total',
        'porcentaje_descuento',
        'descuento_total',
        'total',
        'iva',
    ];

 public function cheque()
    {
        return $this->hasMany('App\Cheque');
    }

这是我在FacturaController中的代码

$factura = Factura::create($request->all());

$factura->cheque()->create($request->cheque);

请求:

{
    "cliente_id" : "3",
    "nombre" : "gustavo",
    "sub_total" : 20000.50,
    "porcentaje_descuento" : 20,
    "descuento_total" : 50,
    "total" : 100,
    "iva" : 12,
    "cheque" : {
                    "1" : {
                            "numero" : "25525886",
                            "banco" : "banesco"
                          }
                }     
}

“支票”已创建,但“ numero”和“ banco”字段留空。

我在做什么错?

预先感谢

2 个答案:

答案 0 :(得分:0)

$factura->cheque($factura_id)->create($request->cheque);

尝试一下。

答案 1 :(得分:0)

    $factura = Factura::create($request->all());
$cheque = Cheque::create($request->only(['input', 'inputenter code here']);
$cheque = factura_id = $factura-id;
$cheque->save();

是这样的