【发布时间】:2020-10-02 00:12:16
【问题描述】:
我正在尝试显示 brands 表中 brand_id 列的值。到目前为止,这是我所做的:
车型
use App\Brand;
class Car extends Model
{
public function brands(){
return $this->belongsToMany(Brand::class);
}
}
品牌型号
use App\Car;
class Brand extends Model
{
protected $fillable = [
'brand_name'
];
public function cars(){
return $this->hasMany(Car::class);
}
}
陈列室控制器
use App\Car;
class ShowroomController extends Controller
{
public function details($name){
$data = Car::where('car_name' , '=', $name)->first();
if ($data == null){
return redirect(route('index'));
}else{
return view('showroom')->with('detail', $data);
}
}
}
展厅视图
@if (isset($detail))
{{ $detail }}
{{ $detail->brands->brand_name }} //this doesn't work
@endif
数据库
品牌表:
+----+------------+
| id | brand_name |
+----+------------+
| 1 | Brand1 |
| 2 | Brand2 |
+----+------------+
汽车表:
+----+----------+----------+
| id | car_name | brand_id |
+----+----------+----------+
| 1 | Car | 1 |
+----+----------+----------+
我在这一点上迷路了。这是处理belongstomany和hasmany关系的正确方法吗?谢谢。
【问题讨论】:
-
尝试加载,你会得到品牌数据
$data = Car::with('brands')->where('car_name' , '=', $name)->first(); -
SQLSTATE[42S02]:未找到基表或视图:1146 表 'databasename_db.brand_car' 不存在(SQL:选择
brands.*、brand_car.car_idas @ 987654333@,brand_car.brand_idaspivot_brand_idfrombrands内连接brand_caronbrands.id=car_id@.brand_idinbrand_id@98654@1 )) -
显示这个错误。
标签: php laravel view relationship has-and-belongs-to-many