【发布时间】:2015-11-18 13:26:44
【问题描述】:
我从一个从表中返回项目数据的基本查询开始:
$project = Project::find($id);
return view('project.show')->with('project', $project);
然后在我的页面上我dd()'d $project->id 并且它起作用了。
我现在还有一个名为 user 的表。
一个项目属于一个用户,所以我在我的模型中设置了一个关系:
public function user()
{
return $this->belongsTo('App\User');
}
然后我会这样做:
$project = Project::with('user')->where('id', $id)->get();
但我得到了错误:
未定义属性:Illuminate\Database\Eloquent\Collection::$id
如果我只是dd()$project:
Collection {#200 ▼
#items: array:1 [▼
0 => Project {#196 ▼
#fillable: array:1 [▶]
#dates: array:2 [▶]
#connection: null
#table: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:5 [▶]
#original: array:5 [▶]
#relations: array:1 [▶]
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
}
我做错了什么?
为了澄清,我希望能够做到:
$project->id
$project->user->name
【问题讨论】:
-
你会在这里找到你的遮阳篷stackoverflow.com/questions/27598603/…
-
您能否提供
projects和users表的架构?
标签: php laravel laravel-5 eloquent relationship