我的表格看起来如此:
用户:
id |用户名|密码| ...
Users_Services
id | user_id | service_id |活跃的| paidTo
和服务:
id |标题|描述|类型|价格|活性
我想从另一个表中获取当前用户的服务及其所有数据,所以我的关系应该是:
我不知道如何在“User_Services”类中执行此操作,在Controller I中:
$ services = User :: find(Auth :: user() - > id) - > services;
用户类:
public function services() {
return $this->hasMany('User_Services');
}
和服务类:
public function user_services()
{
return $this->hasManyThrough('User_Services', 'User', 'service_id');
}
现在User_Services类怎么样,我怎么能做那种关系?
答案 0 :(得分:0)
从User类,您可以声明两种关系。 编辑:我对箭头感到困惑:如果关系是1-N_1-N
class User extends Eloquent {
public function services()
{
return $this->hasManyThrough('Services', 'Users_services');
}
public function usersServices()
{
return $this->hasMany('Users_services');
}
}
如果它是多对多的1-N_N-1 class User扩展了Eloquent {
public function services()
{
return $this->belognsToMany('Services', 'Users_services');
}
}
class Services extends Eloquent {
public function services()
{
return $this->belognsToMany('Users', 'Users_services');
}
}
答案 1 :(得分:0)
我相信你实际上正在寻找一个多对多的关系,在Laravel中将使用belongsToMany()
函数进行定义。你可以这样设置......
class User extends Eloquent {
public function services()
{
return $this->belongsToMany('Service')->withPivot('active', 'paidTo');
}
}
class Service extends Eloquent {
public function users()
{
return $this->belongsToMany('User');
}
}
withPivot()
部分正在抓取User_services
表格中的其他列。
现在获取用户的服务非常简单,可以像这样完成......
$services = Auth::user()->with('services');
foreach($services as $service) {
echo $service->description;
// If you need to display information from the pivot table, that can be done like so.
echo $service->pivot->paidTo;
}