【问题标题】:Laravel: Multiple tables in one modelLaravel:一个模型中的多个表
【发布时间】:2018-06-11 04:12:04
【问题描述】:

我有以下用户模型:

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 函数)从不同的表中获取信息吗?

或者我应该为每个表创建一个模型,然后为每个表“加入它们”hasManybelongsToMany 等)?

编辑:

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

class Dashboard extends Model
{
    protected $table = 'dashboard';

    public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');
        //user_id
    }
}

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

在 User 类中我有:

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

在我的登录控制器中:

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

有人知道问题出在哪里吗?

感谢您的帮助!

【问题讨论】:

  • 你应该为每个表创建一个单独的模型
  • 肯定为每个表创建一个模型

标签: laravel laravel-5


【解决方案1】:
public function dashboards()
{return $this->hasMany(\App\Dashboard::class);
}

在您的仪表板模型中,您可以这样做

protected $casts = [
        'user_id' => 'int',
    ];
public function user()
    {
        return $this->belongsTo(\App\User::class);
    }

【讨论】:

  • 甜,成功了!我这样做的方式有什么问题,我认为这是正确的方式吗?
  • 你忘记了演员表,以及你声明它的方式
  • 我明白了。再次感谢! :)
【解决方案2】:

更多的 Laravel 方法是创建相关的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】:

    您不必在模型中做任何事情!只需引用控制器中的模型即可,例如:

    User::where('id', Auth::id())->pluck('type');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      相关资源
      最近更新 更多