我会先解释一下我的结构,这样你就能明白我想要得到什么
1 - 汽车=姓名-型号-年龄
2 - 用户 = 姓名 - 城市 - 电话
3 - 预订 = from_date - to_date
4- reservation_user = user_id - reservation_id
5 - car_user = user_id - car_id
在 view.blade 中,我尝试在表格中显示用户信息,在该表格下方显示用户请求汽车的描述(他想购买),在该表格下方如果他有车他想租(仅租用)
表用户信息
包含他要求的所有汽车的表格(包括租赁和购买)
包含汽车 ID 和用户想要汽车的日期的表格
public function show($id)
{
$users = User::with('cars')->where( 'id',$id)->get();
return view('show')->withusers($users);
}
我为销售而保存汽车的方式
$id = $new_cars->id;
$user->cars()->attach($id);
出租
$id = $new_car->id;
$R_id = $time->id;
$user->cars()->attach($id);
$user->reservations()->attach($R_id);
问题
出租汽车显示在两个表中,因为在函数中我拉了所有汽车。
问题
我怎样才能只得到一张 table (第三张 table )预订的车?不在第二个表中显示它们
最佳答案
首先,您没有正确设计car_user
数据透视表。您正在该表中存储 User 和 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
关于php - 显示函数的特定数据(laravel),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41210182/