在laravel 5.2中,从一对多关系中的第二个表中获取记录会产生错误


Fetching records from second table in one to many relationship produce error in laravel 5.2

我有两个表,一个是已批准的项目,另一个是艺术家的详细信息。我想获取"项目表"中的"项目名称"数据和"艺术家表"中"艺术家名称"的数据。

我创建了两个关系,它们是

艺术家-模特关系

public function approved_relation()
{
    return $this->hasMany('App'approved_projects_model', 'artist_id');
}

已批准的模型关系

 public function artists_relation()
{
    return $this->belongsTo('App'artists_details_model', 'id');
}

在我的控制器中,我写了以下代码

$art_artist_details = approved_projects_model::with('artists_relation')->get();

   foreach ($art_artist_details as $artists_relationn)
     {
        echo $artists_relationn->category;
        foreach ($art_artist_details as $artists_relationn){
              echo $artists_relationn->artists_relation->phone_no;
          }             
 }

问题是Foreach只循环一次,但当第二次循环到达echo $artists_relationn->artists_relation->phone_no; 时会出现错误

之后,它会给出以下错误"正在尝试获取非对象的属性"我已经做了研究,但好像已经走到了死胡同。请协助。

首先,您不需要第二个循环,所以使用就足够了

$art_artist_details = approved_projects_model::with('artists_relation')->get();
foreach ($art_artist_details as $artists_relationn)
{
   echo $artists_relationn->category;
   echo $artists_relationn->artists_relation->phone_no;                     
}

但从你们的关系来看,你们可能用错了外键。

您应该这样定义关系:

public function artists_relation()
{
    return $this->belongsTo('App'artists_details_model', 'artist_id');
}

此外,你应该确保你在artists_arelation中总是有匹配的记录——如果没有,而不是

echo $artists_relationn->artists_relation->phone_no;

您应该使用:

echo $artists_relationn->artists_relation ? $artists_relationn->artists_relation->phone_no : 'none';