在模型(父)上应用 WHERE 子句时出错,然后在 eloquent 中获取其相关模型(子)数据

getting error when applied WHERE clause on a model(parent) and then gets its related model(child) data in eloquent

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

用户模型:

    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() 子句获取用户模型数据,然后获取其相关项目。

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


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

正如错误所说,您在 Builder

中没有 属性
 $client = User::where('email', $request->input('client'))->projects;

试试这个

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

我们在这里获取 具有特定电子邮件的用户 并加载关系,在这里您 将关系作为对象

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

简短版本:在访问项目之前调用 first()

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

可选:添加 with('projects') 以预先加载项目。不过,这不会为您的情况增加任何性能奖励,因为您只加载了一个模型。

在 HomeController 中,这一行将重新运行数组集合....简单来说,它将 return 多条记录....
$client = User::where('email', $request->input('client'))->projects;

如你所愿单条记录先用()。要检索单个记录...它将重新运行第一个匹配的记录...

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