我在DB(用户,地区,area_user)3台,属性[名]在此集合实例不存在
用户表: ID 名 用户名 密码
地区表: ID 名
area_user表: ID 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的@索引文件:
<?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->区)输入,它会显示所有地区列: -
[
{
"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)中指定了Areas关系中的列名称,则会显示以下错误: -
此集合实例中不存在属性[name]。 (查看:C:\ XAMPP \ htdocs中
我怎么可以在视图文件只显示(areas.name)列
谢谢, 就解决问题串连的名字,现在是区显示,因为它应该。 – user2873860