Update
Laravel 5.3.23, ( , HasOne
). HasOne
withDefault()
. Book
/Author
:
public function author() {
return $this->hasOne(Author::class)->withDefault();
}
( ) Author
, . , , , , ( Author
).
, , , : 16198 16382.
HasOne
. BelongsTo
, MorphOne
MorphTo
, .
, , .
, , , $value
, , null
, . , , .
, , , .
public function getAuthorAttribute($value)
{
$key = 'author';
if (array_key_exists($key, $this->relations)) {
$value = $this->relations[$key];
} elseif (method_exists($this, $key)) {
$value = $this->getRelationshipFromMethod($key);
}
$value = $value ?: new Author();
$this->setRelation($key, $value);
return $value;
}
, hasOne/belongsTo .
, , . , , , dd()
toArray
/toJson
, null
relatioinship .
Model
. .
Model
, Laravel Model
, Model
Laravel Model
.
, setRelation()
. Laravel >= 5.2.30, . Laravel < 5.2.30 getRelationshipFromMethod()
.
MyModel.php
class MyModel extends Model
{
public function setRelation($relation, $value)
{
if (is_null($value)) {
$value = $this->$relation()->getRelated()->newInstance();
}
$this->relations[$relation] = $value;
return $this;
}
protected function getRelationshipFromMethod($method)
{
$results = parent::getRelationshipFromMethod($method);
if (is_null($results)) {
$results = $this->$method()->getRelated()->newInstance();
}
return $this->relations[$method] = $results;
}
}
Book.php
class Book extends MyModel
{
}