2017-10-21 170 views

回答

4

不可以,HasOne关系可以是null,它不需要在数据库中有关联行。只要检查一下就可以了。

此外,您可能需要和新的5.5 optional功能。

它的工作原理就像这样:

optional($user->phone)->number; 

如果你有手机,它将返回数量,但如果它是不是会null而不是Trying to get property of non-object

+0

谢谢。但是,也许你应该改变你的第一个'Nope'到'Yes':D. – Adam

1

除了astratyandmitry我想在我问自己究竟HasOneHasMany之间的区别是什么之后,添加了我发现的以下内容。

首先,它们都具有相同的表结构。

用户表

id | name 
1 | Alice 
2 | Bob 

电话表:

id | user_id | phone 
1 | 1  | 123 
2 | 2  | 321 

方法的hasManyhasOne在类Model是相同的,除了对象,他们退货:

public function hasOne($related, $foreignKey = null, $localKey = null) 
{ 
    $foreignKey = $foreignKey ?: $this->getForeignKey(); 
    $instance = new $related; 
    $localKey = $localKey ?: $this->getKeyName(); 
    return new HasOne($instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey); 
} 

public function hasMany($related, $foreignKey = null, $localKey = null) 
{ 
    $foreignKey = $foreignKey ?: $this->getForeignKey(); 
    $instance = new $related; 
    $localKey = $localKey ?: $this->getKeyName(); 
    return new HasMany($instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey); 
} 

但是,返回的对象(类HasOne和类HasMany)只在3个功能不同:

  • getResults()
  • initRelation()
  • 匹配()

getResults()方法通过神奇__get()方法每当关系称为不带括号称为(参见here)这样

$user->phone 

下面是类hasOnegetResults()方法:

public function getResults() 
{ 
    return $this->query->first() ?: $this->getDefaultFor($this->parent); 
} 

因此输出将是

enter image description here

,如果该关系声明为hasOne

public function phone() 
{ 
    return $this->hasOne('App\Phone'); 
} 

相反从所述getResults()方法的类hasMany由下式给出:

public function getResults() 
{ 
    return $this->query->get(); 
} 

,因此输出是一个空集:

enter image description here

如果关系被声明为hasMany

public function phone() 
{ 
    return $this->hasMany('App\Phone'); 
} 

因此,如果存在数据库中没有关系排,HasOne关系将返回null和astratyandmitry在他的帖子中描述的一个可以处理它。

不幸的是,我找不到方法initRelation()或方法match()被调用。