Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
904 views
in Technique[技术] by (71.8m points)

php - Laravel HasMany relationship Undefined property: IlluminateDatabaseEloquentRelationsHasMany::$id

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

model 1 Project:

namespace App;

use IlluminateDatabaseEloquentModel;

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

public function projectitem()
    {
        return $this->hasMany('AppProjectitem');
    }
}

model 2 Projectitem:

namespace App;

use IlluminateDatabaseEloquentModel;

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

    function project(){

        return $this->belongsTo('AppProject');

    }
}

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.

Any help would be appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

try thhis,

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...