【问题标题】:ErrorException thrown with message "Trying to get property 'subo_name' of non-object抛出 ErrorException 并显示消息“尝试获取非对象的属性 'subo_name'
【发布时间】:2019-12-09 09:23:17
【问题描述】:

ErrorException 与消息一起抛出

“试图获取非对象的属性'subo_name'(查看: C:\xampp\htdocs\org\resources\views\users\index.blade.php)"

主要模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Maino extends Model
{
    protected $fillable = [
        'maino_name'
    ];


     public function subo()
    {
        return $this->hasMany('App\Subo');
    }
}

模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Subo extends Model
{   

    protected $fillable = [
        'subo_name','maino_id'
    ];

    public function maino()
    {   

        return $this->belongsTo('App\Maino');
    }

    public function users()
    {
        return $this->hasMany('App\User');
    }

}

用户模型

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
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',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];



     public function role()
     {
        return $this->belongsTo('App\Role');
     }


     public function profile()
     {
        return $this->hasMany('App\Profileinfo');
     }

     public function suborg()
     {
        return $this->belongsTo('App\Subo');
     }
}

用户控制器代码

public function index()
{  
  // $user=User::all();
     $users=User::all();
     return view('users.index',compact('users'));
}

index.blade.php

    @extends('mainorg.main')
    @section('title','Users')
    @section('content')
    <!-- DataTables Example -->
            @if(Session::has('status'))
                <div class="alert alert-success">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span></button>
                    {{ Session::get('status') }}
                </div>
      @endif
            <div class="card mb-3">

              <div class="card-header">
                <!-- <i class="fas fa-table"></i>
               MainOrg  --><div class="container"><a href="{{URL::asset('users/create')}}"><button class="btn btn-primary float-right">Add SubOrg</button></a></div></div>
              <div class="card-body">
                <div class="table-responsive">
                  <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                    <thead>
                      <tr>
                        <th>id</th>
                        <th>name</th>
                        <th>user</th>
                        <th>main org</th>
                        <th>suborg</th>
                        <th>Edit</th>
                        <th>Delete</th>
                      </tr>
                    </thead>
                    <tfoot>
                      <tr>
                        <th>id</th>
                        <th>name</th>
                        <th>user</th>
                        <th>main org</th>
                        <th>suborg</th>
                        <th>Edit</th>
                        <th>Delete</th>
                      </tr>
                    </tfoot>
                    @foreach($users as $user)
                    <tr>
                        <td>{{$user->id}}</td>
                        <td>{{$user->name}}</td>
                        <td>{{$user->role->role_name}}</td>

                        <td>{{$user->suborg->subo_name}}</td>
                        <td><a href="{{ route('users.edit',$user->id) }}" class="btn btn-success">Edit</a></td>
                        <td><form action="{{route('users.destroy',$user->id)}}" method="post">
            @method('DELETE')
            @csrf
            <input type="submit" name="" value="DELETE" class="btn btn-danger">
          </form></td>

                      </tr>
                      @endforeach

                    <tbody>

                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
          @endsection

我遇到了有关此代码的问题,所以请帮我解决这个问题......................

【问题讨论】:

    标签: laravel


    【解决方案1】:

    当您在两个或多个模型之间创建关系时,您应该在模型使用期间使用关系方法,在您的 eloquent 调用中使用 with,当您想要传递多个 like - with(['suborg', 'example']) 时也可以编写。在索引方法中,波纹管$users 变量使dd($users) 并检查是否有任何关系数据。如果找到我认为,它应该可以工作。

    public function index()
    {  
      // $user=User::all();
         $users=User::with('suborg')->get();
         return view('users.index',compact('users'));
     }
    

    还有你的 index.blade.php

    @foreach($users as $user)
         <tr>
             <td>{{$user->id}}</td>
             <td>{{$user->name}}</td>
             <td>{{$user->role->role_name}}</td>
             <td>{{$user->suborg->subo_name || 'Not Found'}}</td>
             ......
    @endforeach
    

    【讨论】:

    • 试图获取非对象的属性“subo_name”(视图:C:\xampp\htdocs\org\resources\views\users\index.blade.php)这个问题现在面临
    • $users=User::with('suborg')-&gt;get();dd($users)了吗?
    • array:2 [▼ 0 => array:9 [▼ "id" => 1 "name" => "Siddhesh Aldar" "role_id" => 2 "subo_id" => 1 "email " => "itsmealdar@gmail.com" "email_verified_at" => null "created_at" => "2019-07-31 13:47:48" "updated_at" => "2019-07-31 13:47:48" "suborg" => null ] 1 => array:9 [▼ "id" => 2 "name" => "suresh aldar" "role_id" => 1 "subo_id" => 2 "email" => "admin@ gmail.com" "email_verified_at" => null "created_at" => "2019-07-31 14:30:02" "updated_at" => "2019-07-31 14:30:02" "suborg" => null ] ]
    • 您的关系清楚地表明 suborg 为空。这意味着您在 suborg 中没有数据,这就是您收到此错误的原因。如果您想保留 null 并且不显示任何错误,请执行 ` {{ $user->suborg->subo_name || 'Not Found'}}` 如果 suborg 没有值,这将显示为空白。
    【解决方案2】:

    错误意味着您的$users 之一在循环时没有suborg。所以{{ $user-&gt;suborg }}null,你不能访问-&gt;namenull。要处理此问题,请将您的用户限制为仅具有 suborg 的用户,或在循环时检查:

    public function index() {  
      $users=User::with('suborg')->has('suborg')->get();
      return view('users.index',compact('users'));
    }
    

    注意:您可以在单个查询中同时使用withhas;他们做不同的事情。

    或者,在循环你的用户时,检查是否存在:

    @foreach($users as $user)
    <tr>
      <td>
      @if($user->suborg)
      {{ $user->suborg->subo_name }}
      @else
      No Suborg
      @endif
      </td>
    </tr>
    @endforeach
    

    【讨论】:

    • 先生,但两者都有子 ID
    • 您的subo 表中有ids12 的数据库记录?有很多情况可以设置您的id,但这种关系不存在。记录被删除,ids不匹配等。不要依赖它,使用上面的方法来约束记录或检查是否存在。
    猜你喜欢
    • 2015-09-17
    • 1970-01-01
    • 2017-08-02
    • 2018-04-14
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多