Laravel:一个模型中有多个表
我为用户提供了以下模型:Laravel:一个模型中有多个表,laravel,laravel-5,Laravel,Laravel 5,我为用户提供了以下模型: class User extends Authenticatable { use Notifiable; protected $table = 'login_info'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email',
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
函数)
或者我应该为每个表创建一个模型,然后为每个表“连接它们”(有多个,属于多个,等等)
编辑:
我现在使用的是模型,但是查询的结果总是一个空数组
class Dashboard extends Model
{
protected $table = 'dashboard';
public function user()
{
return $this->belongsTo(User::class,'user_id','id');
//user_id
}
}
user\u id
是登录信息表中使用的用户id
在用户类中,我有:
public function dashboards()
{
return $this->hasMany(Dashboard::class,'id','user_id');
}
在登录控制器中,我有:
$user = \App\User::find(1);
$user->dashboards;
有人看到问题出在哪里了吗
谢谢你的帮助 您不必在模型中执行任何操作!只需参考控制器中的模型,例如:
User::where('id', Auth::id())->pluck('type');
您不必在模型中执行任何操作!只需参考控制器中的模型,例如:
User::where('id', Auth::id())->pluck('type');
更广泛的方法是创建相关的仪表板
模型,使用有说服力的关系,并利用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);
}
}
更广泛的方法是创建相关的仪表板
模型,使用有说服力的关系,并利用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);
}
}
在你的仪表板模型中,你是这样做的
protected $casts = [
'user_id' => 'int',
];
public function user()
{
return $this->belongsTo(\App\User::class);
}
在你的仪表板模型中,你是这样做的
protected $casts = [
'user_id' => 'int',
];
public function user()
{
return $this->belongsTo(\App\User::class);
}
你应该为每个表创建一个单独的模型绝对要为每个表创建一个模型你应该为每个表创建一个单独的模型绝对要为每个表创建一个模型真管用!我做这件事的方式有什么问题?我认为这是正确的方式?你忘记了石膏,你宣布它的方式我看到了。再次感谢!:)好极了,成功了!我做这件事的方式有什么问题?我认为这是正确的方式?你忘记了石膏,你宣布它的方式我看到了。再次感谢!:)