laravel 5.3错误:试图获取非对象的属性

时间:2018-05-17 10:15:30

标签: php laravel-5 laravel-5.3

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中尝试上述查询,但我遇到了错误 undefined属性照亮数据库雄辩集合

我的用户模型

<?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   

1 个答案:

答案 0 :(得分:0)

我首先建议在返回视图之前放置一个dd($ userdetails),以便检查它确实是你正在寻找的。

如果需要,请创建一个名为

的变量
$visible = [] 

并将所有可见字段放在其中。