在模型(父级)上应用WHERE子句时出错,然后雄辩地获取其相关的模型(子级)数据

时间:2019-08-16 09:43:12

标签: laravel eloquent eloquent--relationship

我有一个作为父级的用户模型和一个作为子级的项目模型。我在这两者之间建立了一对多的关系,如下所示。

用户模型:

    class User extends Authenticatable
      {
       use Notifiable;

       /**
       * The attributes that are mass assignable.
       *
       * @var array
       */
       protected $fillable = [
         'username', 'email', 'password',
       ];
       /**
       * The attributes that should be hidden for arrays.
       *
       * @var array
       */
       protected $hidden = [
         'password', 'remember_token',
       ];

       /**
       * The attributes that should be cast to native types.
       *
       * @var array
       */
       protected $casts = [
         'email_verified_at' => 'datetime',
       ];

       public function projects(){
          return $this->hasMany('App\Project', 'user_id');
       }
    }

项目模型:

    class Project extends Model
    {
       // Table Name
       protected $table = 'projects';
       //Primary Key
       protected $primaryKey = 'project_id';
       // Timestamps
       public $timestamps = true;

       protected $guarded = [];

       public function user(){
          return $this->belongsTo('App\User', 'user_id');
       }
    }

在用户模型上应用where子句然后获取其相关项目时:

    class HomeController extends Controller
    {
        public function createProject(Request $request){
           $client = User::where('email', $request->input('client'))->projects;
        }
    }

获取错误

   Exception
   Property [projects] does not exist on the Eloquent builder instance.

但是在做

    $client = User::find(id)->projects;

上面的查询给了我结果。

预期结果:我想通过WHERE()子句而不是Find()子句获取用户模型数据,然后获取其相关项目。

4 个答案:

答案 0 :(得分:0)

错误表明您在Builder中没有财产

 $client = User::where('email', $request->input('client'))->projects;

尝试

$client = User::with('projects')->where('email', $request->input('client'))->first()->projects;

在这里,我们通过特定的电子邮件获取用户并加载实况,并在此处将关系作为对象

答案 1 :(得分:0)

问题的根源是您尚未检索到任何用户。在查询构建器上调用first()get()之前,您只能使用查询构建器的功能。

简短版本:访问项目之前,请致电first()

 $client = User::query()
     ->where('email', $request->input('client'))
     ->first()
     ->projects;

可选:添加with('projects')以急于加载项目。不过,这并不会增加任何性能上的好处,因为您只加载一个模型。

答案 2 :(得分:0)

在HomeController中,此行将重新运行数组的集合。...简单来说,它将返回多个记录。...
           $ client = User :: where('email',$ request-> input('client'))-> projects;

如果要单个记录,请首先使用()。要检索单个记录...,它将重新运行第一个匹配的记录...

$client = User::where('email', $request->input('client'))->first()->projects; 

答案 3 :(得分:-1)

class HomeController extends Controller
    {
        public function createProject(Request $request){


     $client = User::with('projects')->where('id');
        }
    }