Laravel HasMany关系未定义的属性:Illuminate \ Database \ Eloquent \ Relations \ HasMany :: $ id [英] Laravel HasMany relationship Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$id

查看:81
本文介绍了Laravel HasMany关系未定义的属性:Illuminate \ Database \ Eloquent \ Relations \ HasMany :: $ id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读取具有关联关系的数据时遇到问题.它如何返回Undefined属性:Illuminate \ Database \ Eloquent \ Relations \ HasMany :: $ id.我不知道自从我刚开始使用laravel以来我做错了什么.

i have a problem with reading out data with a relationship. some how it returns Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$id. I have no clue what i did wrong since i just started using laravel.

模型1项目:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    protected $table = "project";

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

模型2项目:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Projectitem extends Model
{
    protected $table = "project_item";

    function project(){

        return $this->belongsTo('App\Project');

    }
}

index.php

 @foreach ($projects as $project) 
       <tr>
           <td>{{$project->projectitem()->id}}</td>
           <td></td>
      </tr>
     @endforeach

我不知道为什么会发生这种情况,我已经尝试了几种解决方案,但似乎都没有用.

i have no clue why this happens, i've tried a couple of solutions but none seems to work.

任何帮助将不胜感激

推荐答案

查看关系-它具有hasMany关系.意思是,关于项目有很多项目项.

Look at the relation - it is hasMany relation. meaning, on project has many project items.

尝试,

 @foreach ($projects as $project) 
    @foreach ($project->projectitem as $projectitem)
       echo $projectitem->id
    @endforeach
 @endforeach

注意:仅当关系为hasMany时,才需要此内部循环.如果它是hasOne,则无需在循环中更改任何内容,只需将关系更改为hasOne并运行即可.

NOTE: this inner loop is necessary only if the relation is hasMany. if it is hasOne, no need to change anything in you loop, just change the relation to hasOne and run.

这篇关于Laravel HasMany关系未定义的属性:Illuminate \ Database \ Eloquent \ Relations \ HasMany :: $ id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆