【问题标题】:Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name laravel 5.4未定义的属性:Illuminate\Database\Eloquent\Relations\BelongsTo::$name laravel 5.4
【发布时间】:2017-10-30 08:29:13
【问题描述】:

您好,以下是我的关系

用户模型

   public function loginlogout()
    {
        $this->HasMany("App\Models\LoginLogoutLogs");
    }

这是我的 LoginLogoutLogs 模型

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

我正在尝试像这样访问用户的名称

 $loginLogoutLogs = LoginLogoutLogs::all();
        foreach($loginLogoutLogs as $loginLogoutLog){
            dd($loginLogoutLog->users()->name);
        }

但我收到此错误

未定义属性:Illuminate\Database\Eloquent\Relations\BelongsTo::$name

编辑添加模型

<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Session;
use Illuminate\Support\Facades\DB;

class User extends Authenticatable
{
    use Notifiable;
    use EntrustUserTrait;

    protected $table = 'tbl_users';
    protected $primaryKey = 'id';
    protected $guarded = ['id'];
    const API = 'api';
    const WEB = 'web';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'last_login', 'Address', 'Age', 'DateOfBirth', 'created_by', 'deleted_by'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'is_admin' => 'boolean',
    ];

    public function isAdmin()
    {
        return $this->is_admin;
    }

    static function GetUserNamebyID($id)
    {
        $name = User::select("name")->where(["id" => $id])->pluck('name');
        if (isset($name[0])) {
            return $name[0];
        } else {
            return '';
        }
    }



    public function loginlogout()
    {
        $this->HasMany("App\Models\LoginLogoutLogs", 'userID');
    }

    public function company()
    {
        $this->HasMany("App\Models\Company");
    }
}

现在是 LoginLogouts 模型

<?php


namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Illuminate\Database\Eloquent\Model;
use Session;
use Illuminate\Support\Facades\DB;

class LoginLogoutLogs extends Model
{
    use Notifiable;
    use EntrustUserTrait;

    protected $table = 'tbl_users_logs';
    protected $primaryKey = 'id';
    protected $guarded = ['id'];
    const API = 'api';
    const WEB = 'web';


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'userID','is_accpeted','type','addedFrom'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'is_admin' => 'boolean',
    ];

    public function isAdmin()
    {
        return $this->is_admin;
    }

    // change company to hasmany

    public function user()
    {
        return $this->belongsTo('App\Models\User');
    }

}

【问题讨论】:

    标签: php laravel-5.4 has-many belongs-to


    【解决方案1】:

    只需改变你的部分

    dd($loginLogoutLog->users()->name);
    

    进入

    dd($loginLogoutLog->users->name);
    

    移除用户的支架,它很容易修复。 这里我们获得的是一个属性,而不是一个函数......(虽然在模型中它被定义为函数)

    【讨论】:

      【解决方案2】:

      在获取child 模型时删除(),并为belongsTo 添加第二个参数。

      你在这里:

      迁移:

      // Parent migration (create_clients_table):
      Schema::create('clients', function (Blueprint $table) {
        $table->unsignedBigInteger('user_id');
        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
      });
      
      // Child migration (create_payments_table):
      Schema::create('payments', function (Blueprint $table) {
        $table->unsignedBigInteger('client_id');
        $table->foreign('client_id')
            ->references('id')
            ->on('clients')
            ->onDelete('cascade');
      });
      

      模型关系:

      // Child (Client Model)
      public function owner()
      {
        return $this->belongsTo(User::class, 'user_id');
      }
      
      // Parent (User Model)
      public function clients()
      {
        return $this->hasMany(Client::class);
      }
      

      数据输出:

      // Route:
      Route::get('/client/{id}/payments', [PaymentController::class, 'paymentsOfClient']);
      
      
      // In controller (PaymentController):
      /**
       * Display a listing of the payments of specified Client.
       *
       * @param  string  $id
       * @return \Illuminate\Http\Response
       */
      public function paymentsOfClient($id)
      {
          $client = Client::find($id);
      
          // check permissions
          if (auth()->user()->id !== $client->owner->id) {
              return;
          }
      
          $payments = $client->payments()->paginate(20);
          return response()->json($payments);
      }
      
      

      【讨论】:

        【解决方案3】:

        简单修复:

        $loginLogoutLogs = LoginLogoutLogs::all();
        foreach($loginLogoutLogs as $loginLogoutLog){
            dd($loginLogoutLog->users->name);
        }
        

        您想要访问关系实体,而不是关系模型。

        通过使用users(),您的代码认为您正在尝试在users 模型上调用name() 方法,而不是在LoginLogoutLogs 类上调用users 方法。

        【讨论】:

        • 请让我测试一下
        • Trying to get property of non-object 使用您建议的编辑
        • 如果你总是有一个LoginLogoutLogs 和一个User 关系,那么这个答案是正确的,所以你得到Trying to get property of non-object 因为你的$loginLogoutLog-&gt;users 返回null 因为$loginLogoutLog 没有用户关系,或者您在模型上定义了错误的关系。
        • @noobie-php 请查看 Nerea 的评论 - 这就是您收到该错误的原因。
        • @Nerea: 所以我的关系可能有错误,我也应该发布我的模型吗? @詹姆斯?
        【解决方案4】:

        您需要更改与用户的关系,在LoginLogoutLogs 中添加外键:

        public function user()
        {
            return $this->belongsTo('App\Models\User', 'userID');
        }
        

        还要确保你调用 user insted of users

        $loginLogoutLogs = LoginLogoutLogs::all();
        foreach($loginLogoutLogs as $loginLogoutLog){
            dd($loginLogoutLog->user->name);
        }
        

        如果你想执行预加载:

        $loginLogoutLogs = LoginLogoutLogs::with('user')->get();
        foreach($loginLogoutLogs as $loginLogoutLog){
            dd($loginLogoutLog->user->name);
        }
        

        【讨论】:

          猜你喜欢
          • 2018-11-22
          • 2020-11-23
          • 2020-01-26
          • 2020-05-04
          • 2021-09-23
          • 2020-01-29
          • 2018-11-19
          • 2020-07-08
          • 2021-03-12
          相关资源
          最近更新 更多