php - Laravel Eloquent 非常规专栏不起作用

标签 php laravel laravel-4 eloquent laravel-5

嗨,对于多对多的情况,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',
        'mwsOrders_shippingAddress',
        'AmazonOrderId',
        'Address_id'
      );
   }

}

EER 图 enter image description here

现在当我运行这个

$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, AmazonOrderId) values (1, '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',
        'mwsOrders_shippingAddress',
        'AmazonOrderId',
        'Address_id'
    );
}

那么你可以试试这个:

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

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

关于php - Laravel Eloquent 非常规专栏不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29583362/

相关文章:

mysql - Illuminate\Database\Query\Builder 类的对象无法转换为字符串,无法在单个查询中从两个数据库中获取数据

php - bootstrap.min.css 加载资源失败:net::ERR_CONNECTION_REFUSED

php - Imagick max 资源在 php 脚本中与 php 命令行不同

php - MySQL 查询每 60 秒重新启动一次?

Laravel 未连接到 homestead 数据库

php - 在 Laravel 路由中使用参数调用自定义类方法

php - 谷歌索引同一页面的两个 URL - 有和没有 index.php

php - Laravel - 返回本地主机的路由

php - 在 joomla 网站中更改图像路径时出错

php - 上传文件为空 Laravel 5.4