1

我在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;
4

3 回答 3

1

你写的映射代码UserStory Model应该是

public function userAccount(){
        return $this->belongsTo(User::class);
    }

如果您已经编写了此代码,请检查数据库中的列名。

于 2018-05-17T05:55:58.927 回答
1

你可以尝试通过改变这样的顺序:

 $usersStories = User::->select('id','user_id','stories')
                       ->with('userStories')
                       ->get();
 print_r($usersStories);
 exit;
于 2018-05-17T05:56:29.380 回答
1

您应该更新您的模型并尝试:

用户模型

public function userStories(){
        return $this->hasMany(UserStory::class);
    }

用户故事模型

public function users(){
        return $this->belongsTo(User::class, 'user_id');
    }
于 2018-05-17T06:01:19.783 回答