具有自定义列名称的多态关系

时间:2018-12-22 12:11:39

标签: php laravel

我正在一个项目上,模型之间存在多态关系问题

模型是Userspatientdoctor,其中patientdoctor主要是用户,但在某些信息上有所不同。问题是我在为每个模型(而不是code)使用自定义IDs,并尝试检索Patient用户信息时得到并清空用户数组。

我通过将userable_typeuserable_code添加为morphMany关系的参数来查找一些建议的解决方案,但仍然没有结果。

患者迁移:

  Schema::create('patients', function (Blueprint $table) {
        $table->increments('id');
        $table->string('patient_code')->unique();
        $table->string('mother_name')->default('tbd');
        $table->string('weight')->default('tbd');
        $table->string('height')->default('tbd');
        $table->string('blood_type')->default('tbd');
        $table->boolean('completed_personal')->default(false);
        $table->boolean('completed_contact')->default(false);
        $table->boolean('completed_medical')->default(false);
        $table->timestamps();
    });

患者模型:

use Illuminate\Database\Eloquent\Model;

class Patient extends Model
{
    //
    protected $fillable = [
                            'patient_code',
                            'mother_name',
                            'weight',
                            'blood_type',
                            'completed_personal',
                            'completed_contact',
                            'completed_medical',
                        ];

    public function users()
    {
        return $this->morphMany("App\User", "userable", 'userable_type','userable_code');
    }
}

患者控制器:

public function show(Patient $patient)
{
    //
    $parentUser = $patient->users;
    return $patient;
}

用户模型:

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
                            'user_code',
                            'fname',
                            'mname',
                            'lname',
                            'email',
                            'dob',
                            'age',
                            'gender',
                            'insurance_number',
                            'ssn',
                            'avatar',
                            'is_active',
                            'userable_id',
                            'userable_type',
                        ];

    public function userable()
    {
        return $this->morphTo();
    }
} 

我得到的答复:

{
    "id": 2,
    "patient_code": "P2156407",
    "mother_name": "alex",
    "weight": "97",
    "blood_type": "A-",
    "completed_personal": 1,
    "completed_contact": 1,
    "completed_medical": 1,
    "created_at": "2018-12-21 19:52:13",
    "updated_at": "2018-12-21 19:52:13",
    "users": []
}

更新:找到了解决方法,我忘了添加

protected $primaryKey = 'code_column';在我的模型中,现在一切正常。

0 个答案:

没有答案
相关问题