【发布时间】:2018-04-01 10:55:55
【问题描述】:
我在数据库中有 3 个表(用户、区域、区域用户),
用户表: ID 姓名 用户名 密码
区域表: ID 名字
area_user 表: ID 用户身份 area_id
我正在尝试创建一个(列出用户页面),它将显示所有用户表列以及用户分配的区域。
User.php 模型文件
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password','role_id',];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = ['password', 'remember_token',];
public function areas(){
return $this->belongsToMany('App\Area','area_user');
}
Area.php 模型文件:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Area extends Model{
protected $fillable = ['name'];
public function users(){
return $this->belongsToMany('App\User','area_user','area_id','user_id');
}
}
UserController@index 文件:
<?php
namespace App\Http\Controllers;
use App\Areas;
use App\Roles;
use App\User;
use Illuminate\Http\Request;
class UserController extends Controller{
public function __construct(){
// $this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(){
$users = User::get();
return view('users._list',
['users'=> $users]
);
}
最后是表格视图文件:-
@foreach($users as $u)
<tr role="row" class="odd">
<td class="sorting_1">{{$u->name}}</td>
<td></td>
<td>{{$u->areas]}}</td>
<td>{{route('show_user', ['id' => $u->id])}}</td>
</tr></tbody>
@endforeach
如果我只使用区域属性($u->areas)在用户表视图(分配区域)中键入,它将显示所有区域列:-
[
{
"id": 3,
"name": "C",
"location_id": 1,
"created_at": null,
"updated_at": null,
"pivot": {
"user_id": 4,
"area_id": 3
}
},
{
"id": 4,
"name": "D",
"location_id": 2,
"created_at": null,
"updated_at": null,
"pivot": {
"user_id": 4,
"area_id": 4
}
}
]
@foreach($users as $u)
<tr role="row" class="odd">
<td class="sorting_1">{{$u->name}}</td>
<td></td>
<td>{{$u->areas->name]}}</td>
<td>{{route('show_user', ['id' => $u->id])}}</td>
</tr></tbody>
@endforeach
请注意,如果我在上述视图 ($u->areas->name) 中指定区域关系中的列名,则会显示错误:-
此集合实例上不存在属性 [名称]。 (查看:C:\xampp\htdocs
如何在视图文件中只显示 (areas.name) 列
【问题讨论】:
标签: php laravel eloquent laravel-eloquent laravel-query-builder