php – Laravel雄辩的非传统专栏无法正常工作

对于很多情况,嗨laravel没有在数据透视表中插入正确的值.

我的第一个模型是

class ShippingAddress extends Eloquent {
  protected $guarded = array('id');
  protected $table = 'shippingAddress';

  public function mwsOrder()
  {
    return $this->belongsToMany('MwsOrder','mwsOrders_shippingAddress','Address_id','AmazonOrderId'
    );
  }
}

第二种模式是

class MwsOrder extends Eloquent {
  protected $table = 'mwsOrders';
  protected $primaryKey = 'AmazonOrderId';

  public function shippAddress()
  {
    return $this->belongsToMany('ShippingAddress','AmazonOrderId','Address_id'
      );
   }

}

EER图

现在,当我运行这个

$mwsOrder = new MwsOrder;
$mwsOrder->AmazonOrderId = 'Eve 6';
$mwsOrder->save();

$address = new ShippingAddress;
$address->name = 'Naruto Uzumaki';
$address->save();
$address->mwsOrder()->attach($mwsOrder);
//$mwsOrder->shippAddress()->save($address);

laravel抛出错误,这就是laravel尝试运行查询的原因

(SQL: insert into mwsOrders_shippingAddress (Address_id,
AmazonOrderId) values (1,3))

我需要的是生成此查询

insert into mwsOrders_shippingAddress (Address_id,‘Eve 6’)

更新:
架构是:

Schema::create("shippingAddress",function(Blueprint $table)
{
  $table->increments("id");
  $table->string("Name");
  $table->timestamps();
});

Schema::create("mwsOrders",function(Blueprint $table)
{
  $table->increments("id");
  $table->string("AmazonOrderId")->unique();
  $table->timestamps();
});

Schema::create("mwsOrders_shippingAddress",function(Blueprint $table)
{
  $table->increments("id");
  $table->string("AmazonOrderId");
  $table->foreign("AmazonOrderId")->references("AmazonOrderId")->on('mwsOrders');
  $table->integer("shipping_address_id")->unsigned();
  $table->foreign("shipping_address_id")->references('id')->on('shippingAddress');
  $table->timestamps();
});

解决方法

首先将shippAddress更改为:

// Specify the primary key because it's not conventional id
protected $primaryKey = 'AmazonOrderId';

public function shippAddress()
{
    return $this->belongsToMany('ShippingAddress','Address_id'
    );
}

然后你可以试试这个:

$mwsOrder = new MwsOrder;
$mwsOrder->AmazonOrderId = 'Eve 6';
$mwsOrder->save();

$address = new ShippingAddress(['name' => 'Naruto Uzumaki']);
$mwsOrder->shippAddress()->save($address); // Save and Attach

相关文章

laravel的dd函数不生效怎么办
看不懂laravel文档咋办
安装laravel框架出现command怎么办
Laravel开发API怎么使用事务
laravel怎么构建复杂查询条件
laravel如何实现防止被下载