首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >laravel 5.3错误:尝试获取非对象的属性

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

Stack Overflow用户
提问于 2018-05-17 18:15:30
回答 1查看 217关注 0票数 1

Laravel 5.3我正在尝试从表、用户和手机中获取字段

users表具有主键id,而my mobiles表具有字段users_id

所以我想要得到所有users_id的所有号码

代码语言:javascript
复制
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集合

我的用户模型

代码语言:javascript
复制
<?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');
    }

}

我的移动模型

代码语言:javascript
复制
<?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 ();//获取所有用户

代码语言:javascript
复制
$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

代码语言:javascript
复制
@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   
EN

回答 1

Stack Overflow用户

发布于 2018-05-17 20:03:22

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

如果需要,可以创建一个名为

代码语言:javascript
复制
$visible = [] 

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50388914

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档