代码之家  ›  专栏  ›  技术社区  ›  Araw

laravel:一个模型中有多个表

  •  0
  • Araw  · 技术社区  · 8 年前

    我为用户提供了以下模型:

    class User extends Authenticatable
    {
        use Notifiable;
        protected $table = 'login_info';
    
        /**
         * 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 getDashboards()
        {
            return \DB::table('dashboard')
                   ->select('type')
                   ->where('id', Auth::id())
                   ->orderBy('column', 'asc')
                   ->get();
        }
    }
    

    用户在许多表中有不同的信息

    • 用户信息,如姓名、办公室、仪表板、2FA等

    是我现在的做法 “最佳实践” (就像 getDashboards 函数)从不同的表中获取信息?

    或者我应该为每个表创建一个模型,然后 “加入他们” ( hasMany , belongsToMany ,依此类推)对于每个表?

    编辑:

    我现在使用的是模型,但是查询的结果总是一个空数组。

    class Dashboard extends Model
    {
        protected $table = 'dashboard';
    
        public function user()
        {
            return $this->belongsTo(User::class,'user_id','id');
            //user_id
        }
    }
    

    user_id 是登录信息表中使用的用户的ID。

    在用户类中,我有:

    public function dashboards()
    {
        return $this->hasMany(Dashboard::class,'id','user_id');
    }
    

    在登录控制器中,我有:

    $user = \App\User::find(1);
    $user->dashboards;
    

    有人知道会有什么问题吗?

    谢谢你的帮助!

    3 回复  |  直到 8 年前
        1
  •  1
  •   user9025311    8 年前
    public function dashboards()
    {return $this->hasMany(\App\Dashboard::class);
    }
    

    在你的仪表板模型中你是这样做的

    protected $casts = [
            'user_id' => 'int',
        ];
    public function user()
        {
            return $this->belongsTo(\App\User::class);
        }
    
        2
  •  1
  •   Leon Vismer    8 年前

    更大的方式是创造相关的 Dashboard 建模和使用雄辩的关系,并利用orm的特性。包括一个 orderBy 如果你总是需要在那一列排序的话。

    class User extends Authenticatable
    {
        public function dashboards()
        {
            return $this->hasMany(Dashboard::class)
                ->orderBy('column', 'asc');
        }
    }
    
    class Dashboard extends Model
    {
        public function user()
        {
            return $this->belongsTo(User::class);
        }
    }
    
        3
  •  0
  •   Mateusz Czerwiński    8 年前

    你不必在模型里做任何事!只需参考控制器中的模型,例如:

    User::where('id', Auth::id())->pluck('type');
    
    推荐文章