【发布时间】:2018-10-27 13:44:29
【问题描述】:
Laravel 5.3 我正在尝试从表用户和手机中获取字段
users 表有一个主键 id 我的手机表有一个字段 users_id
所以我想获取所有users_id的所有号码
select u.*,m.mobile,ud.name from users u
left join userdetails ud on ud.user_id = u.id
left join mobiles m on m.users_id = u.id
where m.mobiletypes_id = 1 and m.deleted_by is null
我正在 eloquent 中尝试上述查询,但我遇到了一个错误 未定义的属性照亮数据库雄辩的集合
我的用户模型
<?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 = [
'email', 'password','role_id'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function mobile()
{
return $this->hasMany('App\mobile','users_id');
}
public function userdetails()
{
return $this->hasOne('App\Userdetails');
}
}
我的手机型号
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class mobile extends Model
{
protected $primaryKey = 'mobiles_id';
protected $fillable = ['mobile', 'mobiletypes_id', 'users_id', 'created_by', 'updated_by', 'deleted_by', 'created_at', 'updated_at'];
}
我的控制器
公共函数员工视图(){ // $user = User::all(); // 获取所有用户
$userdetails = User::with(['mobile' => function ($query) {
$query->where('mobiletypes_id', 1);
} ,'userdetails'])->get(); // get all userdetails
// $mobile = User::with('mobile')->get();
//$userdetails = User::all();
//return $user;
//return view('employeeview',compact('userdetails'));
return view('employeeview')->with('userdetails', $userdetails);
}
我的观点employeeview.blade.php
@foreach($userdetails as $u)
<tr>
<td>{{$u->id}} </td>
<td>{{$u->userdetails->name}} </td>
<td>{{$u->email}}</td>
@foreach($u->mobile as $um)
<td>{{$um->mobile}}</td>
@endforeach
</tr>
@endforeach
【问题讨论】:
-
用户有很多手机,所以
$u->mobile不是单个手机,而是手机的集合 -
@apokryfos 我已经编辑了一些代码,你现在可以查看
-
你还遇到同样的错误吗?
标签: php laravel-5 laravel-5.3