【问题标题】:Laravel 7 Single row echo belongsToMany relationshipLaravel 7单行回显belongsToMany关系
【发布时间】: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_id as @ 987654333@, brand_car.brand_id as pivot_brand_id from brands 内连接 brand_car on brands.id = car_id@.brand_id in brand_id @98654@1 ))
  • 显示这个错误。

标签: php laravel view relationship has-and-belongs-to-many


【解决方案1】:

更改
return $this->belongsToMany(Brand::class); 到 return $this->belongsTo(Brand::class); 在汽车模型上

还将名称函数重命名为brand。因为汽车只有单一品牌 之后你可以做$detail->brand->brand_name

【讨论】:

  • 还是不行,这里的输出是:Trying to get property 'brand_name' of non-object
【解决方案2】:

嗨,我知道这看起来很简单,感谢@Imboom,我得到了解决问题的提示。我对 Car 模型做了一些更改:

  1. return $this->belongsToMany(Brand::class);return $this->belongsTo(Brand::class)
  2. 重命名函数为brand
  3. 最后,我刚刚添加了'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

谢谢!

【讨论】:

    猜你喜欢
    • 2014-11-23
    • 1970-01-01
    • 2015-02-22
    • 2018-05-19
    • 2018-03-08
    • 2021-03-22
    • 2021-10-17
    • 2019-07-08
    • 1970-01-01
    相关资源
    最近更新 更多