我想显示 brand_id
栏目从 brands
桌子。这是我目前所做的。
车型
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);
}
}
ShowroomController
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 |
+----+----------+----------+
我在这一点上迷茫了。请问这样做属地和hasmany的关系对吗?谢谢,我想从品牌表中显示brand_id列的值。
更改 return $this->belongsToMany(Brand::class)
;至 return $this->belongsTo(Brand::class);
车型上
同时将名称功能改名为 brand
...因为汽车只有单一的品牌,之后你可以做 $detail->brand->brand_name
嗨,我知道这似乎很简单,感谢@Imboom,我得到了一个提示来解决我的问题。我对汽车模型做了一些修改。
return $this->belongsToMany(Brand::class);
改为 return $this->belongsTo(Brand::class)
brand
最后,我刚刚加了 'brand_id'
中指定的列。cars
表。
public function brand(){
return $this->belongsTo(Brand::class,'brand_id');
}
在ShowroomController中,我修改了我的返回语句 detail
到 car
. 请看下面的代码。
public function details($name){
$data = Car::where('car_name' , '=', $name)->first();
if ($data == null){
return redirect(route('index'));
}else{
return view('showroom')->with('car', $data);
}
}
然后在展厅查看。$car->brand->brand_name
.
@if (isset($car))
{{ $car->car_name }}
{{ $car->brand->brand_name }} // Output is Brand1
@endif
谢谢你!