Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...