让我们说,你已经模型国籍:
class Nationality extends Illuminate\Database\Eloquent\Model
{
// other stuff
// relation between Nationality (id) <-> User (nationality_id)
public function users()
{
return $this->hasMany(User::class);
}
// some other stuff
}
请记住,以满足这个约定:
1)您的nationalities
表必须有id
,name
领域
2)你users
表必须有nationality_id
场
和用户模式将是这样的:
class User extends Illuminate\Database\Eloquent\Model
{
// other stuff
// relation between User (nationality_id) <-> Nationality (id)
public function nationality()
{
return $this->belongsTo(Nationality::class);
}
// some other stuff
}
现在,让我们问ORM与相关的东西给数据:
$User = User::with(['nationality'])->find(1);
的观点:
{{ ($User->nationality)? $User->nationality->name : '' }}
名
奖金:
// we made Nationality model to return us all users that has nationality: Australia
$Nationality = Nationality::with(['users'])
->where(['name' => 'Australia'])
->first();
$users = $Nationality->users;
// or
$Nationality = Nationality::with(['users'])->find($nationalityId);
$users = $Nationality->users;
// and of course eager loading is not good when Your users table is huge,
// so better do it simply like this:
$users = User::where('nationality_id', '=', $nationalityId)->paginate(20);
该代码是不正确的通过ID选择用户的情况下,即只独特:'$用户=用户::其中(阵列( 'ID'=> $ ID)) - > with('nationality') - > get();' - 将返回一个对象的数组。所以将' - > get()'改为' - > first()'使其返回一个对象(不是数组中的对象)。第二个时刻是ORM缩写:'find($ id)',所以不要害怕使用它:'User :: with('nationality') - > find($ id)' – num8er
这现在好吗? @ num8er – webDev
正好。很好(: – num8er