![](/img/trans.png)
[英]Relationship between two tables in Eloquent (Laravel) based on a secondary table
[英]How to check eloquent relationship between two tables?
我有两个表, 用户表和用户表中的用户有:
ID
名称
电子邮件
密码
在我有的客户中
ID
顾客ID
package_id
当有人注册时,在用户表中创建ID号并同时在客户表中创建ID:customer_id中的id和customer_id从id-> user中获得相同的值
public function owners()
{
return $this->belongsToMany('App\User', 'customers');
}
现在,我只需要检查注册后当前customer_id的package_id是否为空或为null即可返回。否则,是否有任何数字返回...我在控制器中尝试了此操作但不起作用
public function redirectpackage(Request $request)
{
if (Auth::check() && Auth::user()->customer->package_id == 1) {
return view('index.customer.customerpackage');
}
else{
return view('index.customer.customerabout');
}
}
如果customers.customer_id
是引用users.id
的外键,则:
因此,在owners()
内部,将belongsToMany()
owners()
替换为belongsTo()
:
public function owners()
{
return $this->belongsTo('App\User', 'customer_id');
}
在User
模型内部,向Customer
模型添加一个关系:
class User extends Model
{
public function customers()
{
return $this->hasMany('App\Customer', 'customer_id');
}
}
现在,您可以检查用户在customers()
关系中是否具有给定的package_id
:
Auth::user()->customers()->where('package_id', 1)->count();
另外,您可以使用isEmpty()
代替count()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.