【问题标题】:How to check eloquent relationship between two tables?如何检查两个表之间的雄辩关系?
【发布时间】:2018-04-24 05:09:53
【问题描述】:

我在 users 表中有两个表,customers 和 users 我有:

身份证

名字

电子邮件

密码

在我拥有的客户中

身份证

customer_id

package_id

当有人注册时,在user表中创建id号,同时在customers表中创建:id和customer_id从id->user获取相同的值 我有内部客户模型

 public function owners()
 {
 return $this->belongsToMany('App\User', 'customers');
}

我现在只需要在注册后检查当前 customer_id 的 package_id 是否为空或 null 返回.. 否则如果有任何数字返回... 我在 controller 中尝试过,但不起作用

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');    
 }
  }

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    如果customers.customer_id 是引用users.id 的外键,则:

    • 一个客户只能有一个用户(“属于”)。
    • 但是一个用户可以有许多个客户(“有很多”)。

    所以,在 owners() 内部将 belongsToMany() 替换为 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()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-12
      • 2020-01-13
      • 2015-03-07
      • 2019-11-06
      • 2018-07-24
      • 2019-07-01
      • 2020-07-23
      • 1970-01-01
      相关资源
      最近更新 更多