我在User
模型与StoryModel
之间建立了关系。但它给了我错误: -
在模型[App \ User]上调用未定义的关系[userStories]。
可能是我错过了什么。以下是我正在使用的代码
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Notification;
use App\CheckIn;
use App\Travel;
use Carbon\Carbon;
use App\NewInterest;
use App\UserStory;
class User extends Authenticatable
{
use Notifiable;
protected $table = "users";
protected $primaryKey = 'id';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'firstname','lastname', 'user_id','email',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function userStories(){
return $this->hasMany(UserStory::class, 'user_id', 'user_id');
}
}
Controller Logic
$usersStories = User::with('userStories')
->select('id','user_id','stories')
->get();
print_r($usersStories);
exit;
答案 0 :(得分:1)
您是否在UserStory Model
中映射了应该
public function userAccount(){
return $this->belongsTo(User::class);
}
如果您已编写此代码,请检查数据库中的列名称。
答案 1 :(得分:1)
你能尝试改变这样的顺序:
$usersStories = User::->select('id','user_id','stories')
->with('userStories')
->get();
print_r($usersStories);
exit;
答案 2 :(得分:1)
您应该更新模型并尝试:
用户模型
public function userStories(){
return $this->hasMany(UserStory::class);
}
UserStory模型
public function users(){
return $this->belongsTo(User::class, 'user_id');
}