首先,您没有正确设计您的car_user 数据透视表。您将User and Car 的关系存储在该表中,但是您使用相同的属性存储两种类型的关系数据,用于出售和出租,并且无法区分哪个是出售的,哪个是出租的。因此,首先,您必须使用该数据透视表中的另一个字段来区分两种类型的关系,因此让我们在表中添加另一个字段,以便您找出关系类型,例如:
表car_user:
user_id | car_id | type
------------------------
1 | 1 | buy
1 | 2 | rent
在这里,类型将用于标识关系的类型,无论是出租还是出售。因此,当您附加关系时,请添加类型字段(租/买),但在此之前,您必须为它们建立关系。因此,您可以在User 模型中使用两种独立的关系方法,例如:
// For Rent
public function rentingCars()
{
return $this->belongsToMany(Car::class)
->wherePivot('type', 'rent')
->withPivot('type');
}
// For Buy
public function buyingCars()
{
return $this->belongsToMany(Car::class)
->wherePivot('type', 'buy')
->withPivot('type');
}
// For both types
public function buyingCars()
{
return $this->belongsToMany(Car::class)->withPivot('type');
}
现在,您可以使用以下方式查询某些类型的汽车:
public function show($id)
{
// Load all cars the user wants to buy
$users = User::with('buyingCars')->where( 'id', $id)->get();
// Notice "withUsers" not "withusers" (you've used "withusers")
// Or: view('show')->with('users', $users);
return view('show')->withUsers($users);
// More examples:
// Load all cars the user wants to rent
// $users = User::with('rentingCars')->where( 'id', $id)->get();
// Load all cars the user wants to buy or sell
// $users = User::with('cars')->where( 'id', $id)->get();
}
现在,当您将汽车附加到 User 模型时,您还必须传递 type 字段的值:
// For rent
$user->cars()->attach($car_id, ['type' => 'rent']);
// For buy
$user->cars()->attach($car_id, ['type' => 'buy']);
另外,当你做这样的事情时:
$user = User::with('cars')->find(1);
您可以使用以下方式查看汽车是出租还是购买:
@foreach($user->cars as $car)
{{ $car->name }}
// Either buy or rent
{{ $car->pivot->type }}
@endforeach