【问题标题】:Method Illuminate\Database\Eloquent\Collection::hasAnyUnit does not exist方法 Illuminate\Database\Eloquent\Collection::hasAnyUnit 不存在
【发布时间】:2020-01-03 09:05:46
【问题描述】:

我想显示来自数据库的检查状态,当我在视图中添加 {{ $mod->hasAnyUnit($unit->kd_unit)?'checked':'' }} 时,我得到了错误

我有单位表,比如角色表:

-------------------
id | kd_unit | name
-------------------
1  | 01      | A
2  | 02      | B
2  | 03      | C
-------------------

第二个是 rs 表,类似于 users 表:

-------------------
id | kd_rs| name
-------------------
1  | 01   | ASD
2  | 02   | ZXC
-------------------

第三个是 mod 表,就像一个角色用户:

-------------------
id | kd_rs| kd_unit
-------------------
1  | 01   | 01
2  | 01   | 02
3  | 01   | 03
-------------------

模型表中的我的模型:

class TManagerOnDuty extends Model
{
    public function units() {
        return $this->belongsToMany('App\Unit', 'kd_unit', 'kd_unit');
    }

    public function hasAnyUnits($units) {
        return null !== $this->units()->whereIn('kd_unit', $units)->first();
    }

    public function hasAnyUnit($unit) {
        return null !== $this->units()->where('kd_unit', $unit)->first();
    }
}

我的控制器:

class ManagerOnDutyController extends Controller
{
  public function edit($kd_rs)
    {
        $units = Unit::orderBy('nm_unit', 'asc')->where('is_active', true)->get();
        $mod = TManagerOnDuty::where('kd_rs', $kd_rs)->get(); 
        return view('layouts.manageronduty.edit')->with([
            'mod'   => $mod,
            'units' => $units,
            'kd_rs' => $kd_rs
        ]);
    }
}  

我的看法:

@foreach($units as $unit)
    <div class="custom-control custom-checkbox mb-3">
        <input name="unitRS[]" value="{{$unit->kd_unit}}" {{ $mod->hasAnyUnit($unit->kd_unit)?'checked':'' }} id="customCheck{{$unit->kd_unit}}" class="custom-control-input" type="checkbox">
        <label class="custom-control-label" for="customCheck{{$unit->kd_unit}}">{{$unit->nm_unit}}</label>
    </div>
@endforeach

我的错误:

我的预期:

【问题讨论】:

  • 您收到什么错误?
  • 等等,我会添加我的错误图片
  • @Fenz 通过dd($mod);检查你在$mod中得到了什么
  • @PrashantDeshmukh ..... 这是 dd($mod) dd-image 的结果

标签: php laravel laravel-5.8


【解决方案1】:

试试这个

$mod = TManagerOnDuty::where('kd_rs', $kd_rs)->first();

在您的控制器中,get 返回一组对象,您不能从该组调用您的hasAnyUnit(),因此首先从您的查询中调用一个对象,然后将其与 hasAnyUnit()

【讨论】:

  • 更改 $mod = .... 我得到这样的错误:link
猜你喜欢
  • 2020-11-21
  • 2021-09-08
  • 2020-11-13
  • 2019-12-11
  • 2020-02-04
  • 2019-11-12
  • 2019-05-24
  • 2019-09-04
  • 1970-01-01
相关资源
最近更新 更多