在模型中设置了雄辩性关系后,我无法在视图中显示关系。
在模型中:Art_obj
class Art_obj extends Model
{
protected $table = 'art_objs';
protected $fillable = ['Id_no','Artist','Year','Title','Description','Origin','Epoch','Picture','Type_of_art'];
public function Painting(){
return $this->hasOne(Painting::class,'Id_no');
}
}
在模型中:绘画
class Painting extends Model
{
protected $table = 'paintings';
protected $fillable = ['art_obj_Id_no','Paint_type','Drawn_on','Style'];
public function Art_obj(){
return $this->belongsTo(Art_obj::class,'Id_no');
}
}
在PaintingController中
public function index()
{
$paintings = Painting::with('Art_obj');
return view('ArtObj.Painting', compact('paintings'));
}
in Painting.blade.php
<table class="table table-bordered table-striped">
<tr>
<th>Title</th>
<th>Paint type</th>
<th>Drawn on</th>
<th>Style</th>
</tr>
@foreach($paintings as $row)
<tr>
<td>{{$row->Art_obj->Title}}</td>
<td>{{$row['Paint_type']}}</td>
<td>{{$row['Drawn_on']}}</td>
<td>{{$row['Style']}}</td>
</tr>
@endforeach
</table>
它在视图中没有任何字段显示。 enter image description here
答案 0 :(得分:1)
如果您没有使用id
作为模型的主键,则需要在模型中设置主键属性:
protected $primaryKey = 'Id_no';
Eloquent还将假定每个表都有一个名为
id
的主键列。您可以定义protected $primaryKey
属性以覆盖此约定。此外,Eloquent假定主键是一个递增的整数值,这意味着默认情况下,主键将自动转换为int值。如果希望使用非增量或非数字主键,则必须将模型上的公共$ incrementing属性设置为false。如果主键不是整数,则应将模型上的
protected $keyType
属性设置为字符串。
此外,该关系必须设置正确的外键和所有者键:
public function Art_obj(){
return $this->belongsTo(Art_obj::class,'Id_no', 'art_obj_Id_no');
}
,然后检索数据:
$paintings = Painting::with('Art_obj')->get();
在尝试访问该关系之前,还应该检查该关系是否存在:
@foreach($paintings as $row)
<tr>
@if (!is_null($row->Art_obj))
<td>{{$row->Art_obj->Title}}</td>
@else
<td>No Title</td>
@endif
<td>{{$row->Paint_type}}</td>
<td>{{$row->Drawn_on}}</td>
<td>{{$row->Style}}</td>
</tr>
@endforeach
答案 1 :(得分:-1)
您尚未提取数据。将查询更改为:
try {
if (hasAccess(userName)){}
} catch (Exception e) {
//caught
}