我正在使用Laravel,并且尝试使用HasOne :: create方法从数组创建相关记录。它插入相关记录,但不向主模型的外部字段添加新的ID。我在做什么错了?
Thx
$contact = new Contact();
$contact->company = $data['company'] ?? '';
$contact->comment = $data['comment'] ?? '';
$contact->save();
$contact->address()->create($data['address']);
...
var_dump($contact->address_id); exit();
在所有字段均已指定的情况下,关系正常运行。通过-> get()方法,他们可以返回正确的模型
var_dump结果-空
此外,$ data ['address']包含有效数据,在Address模型中指定为可填充,而contact_model中可填充address_id
UPD:
联系方式:
public function address()
{
return $this->hasOne(Address::class, 'id', 'address_id');
}
地址类别:
public function contact()
{
return $this->belongsTo(Contact::class, 'id', 'address_id');
}
$ data ['address']包含一个带有['raw'=>'someaddress']的数组,原始字段位于$ fillable
答案 0 :(得分:1)
关于口才关系here,有一个不错的指南。
基于此,我刚刚测试了下面的代码,并且工作正常(使用Laravel 5.8)
迁移
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Cars extends Migration
{
public function up()
{
Schema::create('owners', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('cars', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
$table->integer('owner_id')->unsigned()->index()->nullable();
$table->foreign('owner_id')->references('id')->on('owners');
});
}
public function down()
{
Schema::drop('cars');
Schema::drop('owners');
}
}
模型
//App/Owner.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Owner extends Model
{
protected $fillable = ['name'];
public function car()
{
return $this->hasOne(Car::class);
}
}
//App/Car.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Car extends Model
{
protected $fillable = ['name'];
public function owner()
{
return $this->belongsTo(Owner::class);
}
}
测试
<?php
namespace Tests\Feature;
use App\Owner;
use Tests\TestCase;
class TestCars extends TestCase
{
/**
* A basic feature test example.
*
* @return void
*/
public function testExample()
{
$owner = new Owner(['name' => 'Jack']);
$owner->save();
$owner->car()->create(['name' => 'Nice Car']);
}
}
SQL
select * from cars;
------------
# id, name, created_at, updated_at, owner_id
'1', 'Nice Car', '2019-06-21 13:08:58', '2019-06-21 13:08:58', '1'
select * from owners
-------------
# id, name, created_at, updated_at
'1', 'Jack', '2019-06-21 13:08:58', '2019-06-21 13:08:58'