为什么我无法在 laravel 5.5 中使用一对多关系检索数据
Why I can't retrieve data using a one-to-many relationship in laravel 5.5
我正在尝试 return 我的数据库中的数据,我希望它包含来自相关 table 的数据。这是一对多的关系。但是我得到的只是一个错误
Property [User] does not exist on this collection instance.
在我的用户模型中我有
//App\User.php
class User extends Authenticatable{
use Notifiable;
public function systems(){
return $this->hasMany(\App\Models\General\systems::class,'added_by','id');
}
另一个模型,称为我有的系统
//App\Models\General\systems.php
class systems extends Model
{
public function User(){
return $this->belongsTo(\App\User::class,'added_by','id');
}
在我的控制器中我有
$this->systemsObject = new \App\Model\General\systems();
$systems = $this->systemsObject->get()->User;
根据 Laravel 文档,这应该有效,但事实并非如此。我试着把国外的key/local键参数颠倒过来。我将 ->User 设为大写,小写。
我不知道我做错了什么
您需要迭代 ,例如:
$systems = $this->systemsObject->get();
foreach ($systems as $system) {
echo $system->User->name;
}
我正在尝试 return 我的数据库中的数据,我希望它包含来自相关 table 的数据。这是一对多的关系。但是我得到的只是一个错误
Property [User] does not exist on this collection instance.
在我的用户模型中我有
//App\User.php
class User extends Authenticatable{
use Notifiable;
public function systems(){
return $this->hasMany(\App\Models\General\systems::class,'added_by','id');
}
另一个模型,称为我有的系统
//App\Models\General\systems.php
class systems extends Model
{
public function User(){
return $this->belongsTo(\App\User::class,'added_by','id');
}
在我的控制器中我有
$this->systemsObject = new \App\Model\General\systems();
$systems = $this->systemsObject->get()->User;
根据 Laravel 文档,这应该有效,但事实并非如此。我试着把国外的key/local键参数颠倒过来。我将 ->User 设为大写,小写。
我不知道我做错了什么
您需要迭代
$systems = $this->systemsObject->get();
foreach ($systems as $system) {
echo $system->User->name;
}