我尝试了文档中的示例。我有两个课程:
namespace App;
use Moloquent\Eloquent\Model as Eloquent;
class Author extends Eloquent
{
protected $fillable = [ 'name' ];
}
class Book extends Eloquent
{
public function author()
{
return $this->embedsOne(Author::class);
}
}
在修补程序会话中,我创建了一个作者和一本书,并尝试保存链接:
>>> $author = new App\Author(['name'=>'John Doe']);
=> App\Author {#2284
name: "John Doe",
}
>>> $book = new App\Book();
=> App\Book {#2277}
>>> $book->author()->save($author);
=> App\Author {#2284
name: "John Doe",
updated_at: MongoDB\BSON\UTCDateTime {#2296
+"milliseconds": "1534969446023",
},
created_at: MongoDB\BSON\UTCDateTime {#2296},
_id: MongoDB\BSON\ObjectId {#2298
+"oid": "5b7dc6662dab0d03621a1c82",
},
}
>>> $book->save();
=> true
但是,没有与图书一起存储的作者。
>>> $book
=> App\Book {#2277
updated_at: MongoDB\BSON\UTCDateTime {#2268
+"milliseconds": "1534969455111",
},
created_at: MongoDB\BSON\UTCDateTime {#2268},
_id: MongoDB\BSON\ObjectId {#2294
+"oid": "5b7dc66f2dab0d03621a1c83",
},
}
>>> $book->author
=> null
它坏了,还是我做错了?当我使用 create() 方法时,我得到了一个干净的结果:
>>> $book->author()->create(['name'=>'Jane Doe']);
=> App\Author {#2302
name: "Jane Doe",
updated_at: MongoDB\BSON\UTCDateTime {#2308
+"milliseconds": "1534970275755",
},
created_at: MongoDB\BSON\UTCDateTime {#2308},
_id: MongoDB\BSON\ObjectId {#2317
+"oid": "5b7dc9a32dab0d03621a1c84",
},
}
>>> $book
=> App\Book {#2277
updated_at: MongoDB\BSON\UTCDateTime {#2268
+"milliseconds": "1534969455111",
},
created_at: MongoDB\BSON\UTCDateTime {#2268},
_id: MongoDB\BSON\ObjectId {#2294
+"oid": "5b7dc66f2dab0d03621a1c83",
},
author: App\Author {#2310
name: "Jane Doe",
updated_at: MongoDB\BSON\UTCDateTime {#2308
+"milliseconds": "1534970275755",
},
created_at: MongoDB\BSON\UTCDateTime {#2308},
_id: MongoDB\BSON\ObjectId {#2309
+"oid": "5b7dc9a32dab0d03621a1c84",
},
},
}
尝试使用 save() 方法更改作者仍然无效:
>>> $book->author()->save(App\Author::first())
=> App\Author {#2352
_id: MongoDB\BSON\ObjectId {#2342
+"oid": "5b7dcdfd2dab0d03621a1c85",
},
name: "Your Name",
updated_at: MongoDB\BSON\UTCDateTime {#2346
+"milliseconds": "1534971389628",
},
created_at: MongoDB\BSON\UTCDateTime {#2347
+"milliseconds": "1534971389628",
},
}
>>> $book
=> App\Book {#2277
updated_at: MongoDB\BSON\UTCDateTime {#2292
+"milliseconds": "1534970479148",
},
created_at: MongoDB\BSON\UTCDateTime {#2268
+"milliseconds": "1534969455111",
},
_id: MongoDB\BSON\ObjectId {#2294
+"oid": "5b7dc66f2dab0d03621a1c83",
},
author: App\Author {#2310
name: "Jane Doe",
updated_at: MongoDB\BSON\UTCDateTime {#2308
+"milliseconds": "1534970275755",
},
created_at: MongoDB\BSON\UTCDateTime {#2308},
_id: MongoDB\BSON\ObjectId {#2309
+"oid": "5b7dc9a32dab0d03621a1c84",
},
},
}
问候!
伯恩哈德