我想加载用户,该用户在存储的邀请表中具有适当的url。不幸的是,我没有编写查询。如何切换到“邀请”表并仍然将合适的用户加载到页面上?
关系:
一对一
路线
Route::get('/invite/{url}', 'Auth\RegisterController@show')->name('invite.show');
表邀请:
Schema::create('invites', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->text('greeting')->nullable();
$table->string('url')->unique();
$table->timestamps();
});
功能
public function show($url)
{
$user = User::where(function ($query) use ($url) {
$query->where('invites.url', '=', $url);
})->first();
return view('invite_user', compact('user'));
}
答案 0 :(得分:1)
尝试一下:
$user = User::whereHas('invites', function($query) use($url) {
$query->where('url', $url);
})->first();
请确保您的invites
模型中具有User
关系函数,如下所示:
public function invites() {
return $this->hasMany(Invite::class, 'user_id');
}