Laravel 5.3我正在尝试从表、用户和手机中获取字段
users表具有主键id,而my mobiles表具有字段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进行上述查询,但遇到了一个错误,未定义的属性说明数据库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'];
}我的控制器
public function employeeview(){ // $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 发布于 2018-05-17 20:03:22
我首先建议在视图返回之前放置一个dd($userdetails),以便检查它是否确实是您要查找的内容。
如果需要,可以创建一个名为
$visible = [] 并将所有可见字段放入其中。
https://stackoverflow.com/questions/50388914
复制相似问题