【发布时间】:2021-01-07 03:49:46
【问题描述】:
我有一个问题,当我删除与该住宅相关的承包商时,索引视图<li>Contractor: {{$res->contractor->name}} 的这一行中会出现类似trying to get property name 的错误。我想通过删除承包商使其成为可能,然后住宅视图中的承包商字段可以为空或为空。反之亦然。我怎样才能做到这一点?这是我的模型。
Residential.php
class Residential extends Model
{
protected $fillable = ['name','res_code','postcode','city','state','image','contractor_id'];
public function contractor()
{
return $this->belongsTo(Contractor::class);
}
public function buyer()
{
return $this->hasMany(Buyer::class);
}
}
Contractor.php
class Contractor extends Model
{
protected $table = 'contractors';
protected $fillable = ['name','address','phone_no','email','avatar'];
public function residential()
{
return $this->hasMany(Residential::class);
}
public function users()
{
return $this->morphMany(User::class, 'typable');
}
}
这是我的控制器。
ResidentialController.php
class ResidentialController extends Controller
{
public function index(Request $request)
{
$contractor = Contractor::find($request->id);
$residential = Residential::all();
return view('residentials.index',compact('residential','contractor'));
}
ContractorController.php
public function index(Request $request)
{
$residential = Residential::find($request->id);
$contractor = Contractor::all();
return view('admins.contractors.index', compact('residential', 'contractor'));
}
这是我的观点。
住宅\index.blade.php
@foreach($residential as $res)
<div class="panel-body">
<ul class="list-unstyled list-justify">
<li>ID: {{$res->id}}</li>
<li>Code: {{$res->res_code}}</li>
<li>Postcode: {{$res->postcode}}</li>
<li>City: {{$res->city}}</li>
<li>State: {{$res->state}}</li>
<li>Contractor: {{$res->contractor->name}}
</ul>
</div>
@endforeach
承包商\index.blade.php
<table class="table table-hover" id="contractor-table">
<tr>
<th>ID</th>
<th>Company</th>
<th>Phone No</th>
<th>Email</th>
<th>Residence</th>
<th>Action</th>
</tr>
@foreach($contractor as $cont)
<tr class="contractor{{$cont->id}}">
<td>{{$cont->id}}</td>
<td><a href="/contractor/{{$cont->id}}/profile">{{$cont->name}}</a></td>
<td>{{$cont->phone_no}}</td>
<td>{{$cont->email}}</td>
<td>{{$cont->residential->pluck('name')->implode(', ')}}</td>
@endforeach
</table>
希望有人能理解我的问题并帮助我。
【问题讨论】:
-
通常你会在显示任何属性之前检查关系数据是否存在
-
{{ optional($res->contractor)->name ?? 'n/a' }} -
谢谢@Tpojka,这是我能做的最简单的事情。
标签: php laravel relationship one-to-many