簡體   English   中英

如何在Laravel中連接用戶和地址模型

[英]How to connect User and Address Model in Laravel

我試圖在Laravel中連接兩個模型,一個是默認的用戶模型,另一個是地址模型,但是在連接這兩個模型時遇到了一些麻煩。

用戶模型為

    <?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;
use App\Address;

class User extends Authenticatable
{
    use 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',
    ];

    public function address()
    {
        return $this->hasOne('App\Address');
    }
}

地址模型是

 <?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\User;
use Session;

class Address extends Model
{
    protected $table = 'usercontacts';
    public function address()
    {
      return $this->belongsTo('App\User');
    }
}

這如何正常工作? 任何提示都會有所幫助。 提前致謝

首先,根據定義關系的方式,在usercontacts表中是否有一個名為user_id

如果沒有,您將需要一個。 或者,如果您使用其他特定的外鍵(例如, belongs_to_user_id ,則必須將其指定為hasOne關系中的第二個參數。 例如

// User.php
return $this->hasOne('App\Address', 'belongs_to_user_id');

您可以分享與我們一起收到的錯誤消息嗎?

在地址模型上更改公共功能address(){......}

公共職能用戶 (){.....}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM