【问题标题】:ErrorException Trying to get property 'User' of non-object ( laravel )ErrorException 试图获取非对象(laravel)的属性“用户”
【发布时间】:2021-07-19 21:17:13
【问题描述】:

我收到错误:

ErrorException Trying to get property 'User' of non-object

从以下似乎不起作用的陈述中:

$user = Mobile::find(3)->User;

dd($user);

其余代码如下:

usercontroller.php

<?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\Models\User;
    use App\Models\Mobile;
    use Hash;
    
    class UserController extends Controller
    {
        public function addUserMobile()
        {
            $user = new User;
            $user->name = "Test Name";
            $user->email = "test@mnp.com";
            $user->password = Hash::make("12345678");
            $user->save();
    
            $mobile = new Mobile;
            $mobile->mobile = '123456789';
            $user->mobile()->save($mobile);
        }
        public function index()
    {
        // get user and mobile data from User model
        $user = User::find(3);
        // var_dump($user->name);
        // var_dump($user->mobile->mobile);
    
        // // get user data from Mobile model
        $user = Mobile::find(3)->User;
        dd($user);
    
        // // get mobile number from User model
        //  $mobile = User::find(3)->mobile;
        // dd($mobile);
    }
    }

mobile.php

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

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

    /**
     * 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 mobile()
    {
        return $this->hasOne(Mobile::class);
        // note: we can also inlcude Mobile model like: 'App\Mobile'
    }
}

mobile table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateMobilesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
{
    Schema::create('mobiles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        $table->string('mobile');
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users')
            ->onDelete('cascade');
    });
}

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('mobiles');
    }
}

移动数据库

用户数据库

“3”是 user_id 顺便说一句。

【问题讨论】:

标签: php laravel eloquent


【解决方案1】:

问题是您正在使用 id 3(不存在)查询 Mobile,然后调用 user 关系。

$user = Mobile::find(3)->user;

由于带有不存在 id 的 Mobile::find 返回 null,因此您在 null 上调用 -&gt;user,您将收到您提到的错误。

此外,您应该在移动模型中添加belongsTo 关系:

public function user()
{
    return $this->belongsTo(User::class);
} 

现在,在将查询修复为使用 user_id 之后,您可以执行以下操作:

$user = Mobile::where('user_id', 3)->first()->user;

【讨论】:

    猜你喜欢
    • 2017-08-02
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 2016-11-30
    • 2017-02-25
    • 1970-01-01
    相关资源
    最近更新 更多