我是laravel的新手可以有人帮忙吗?
表格结构
1) rooms
id |roomno |roomtype_id |luxurytype |status
2) roomtypes
id| code| description
模型代码
1)房型模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class roomtype extends Model
{
public function rooms(){
return $this->hasMany('App\room');
}
}
2)房型
namespace App;
use Illuminate\Database\Eloquent\Model;
class room extends Model
{
public function roomtypes(){
return $this->belongsTo('App\roomtype');
}
}
控制器
public function index()
{
$roomtype = roomtype::all();
$rooms = room::all();
return view('home', array('roomtype'=>$roomtype , 'rooms'=>$rooms));
}
查看
@foreach ($rooms as $rooms)
<tr>
<td>{{ $rooms->roomno }}</td>
<td>{{ $rooms->luxurytype }}</td>
<td>{{ $rooms->roomtypes->description }}</td>
<td>{{ $rooms->status }}</td>
<td></td>
</tr>
@endforeach
错误
如果我使用这一行{{ $rooms->roomtypes->description }}
,那么我会得到:
试图获得非对象的属性
(查看:C:\ xampp \ htdocs \ hms \ resources \ views \ home.blade.php)
如何向房间显示房型描述?
答案 0 :(得分:1)
像这样更改您的控制器文件
public function index()
{
$rooms = room::with('roomtypes')->get();
return view('home', array('rooms'=>$rooms));
}
现在按照以下方式访问刀片视图中的房间类型 - :
@foreach ($rooms as $rooms)
<tr>
<td>{{ $rooms->roomno }}</td>
<td>{{ $rooms->luxurytype }}</td>
<td>{{ $rooms->roomtypes[0]->description }}</td>
<td>{{ $rooms->status }}</td>
<td></td>
</tr>
@endforeach