【问题标题】:Combine two request into one using laravel使用 laravel 将两个请求合二为一
【发布时间】:2015-10-26 15:05:10
【问题描述】:

我有两个表电子邮件 (email_id, email) 和用户 (user_id) 与数据透视表 user_email (id, user_id, email_id) 我想检查我的电子邮件“toto@toto.com”是否存在user_id "2"。

$emailID = Email::where('email', 'toto@toto.com')->pluck('id');
$exists = User::find('2')->emails->contains($emailID);

结果还可以,但我想知道是否可以使用 Eloquent 将其合并到一个查询中。

如果有这些型号:

class Email extends Model {
    public function users() {
        return $this->belongsToMany('App\User', 'user_email');
    }
}

class User extends Model {
    public function emails() {
        return $this->belongsToMany('App\Email', 'user_email');
    }
}

【问题讨论】:

    标签: laravel laravel-5 eloquent


    【解决方案1】:

    您也可以使用关系进行查询:

    $email_address = 'toto@toto.com';
    $user_id = 2;
    
    $email = Email::whereHas('users', function($q) use ($user_id) {
        $q->where('users.id', $user_id);
    })->where('email', $email_address)->first();
    
    if($email->exists) {
        //... it exists
    }
    

    【讨论】:

      【解决方案2】:

      是的,你可以这样做。

      public function getUserById($id) {
          $user = User::with('emails')->where('id', 2)->first();
      
          return view('your-view')->with('user', $user);
      }
      

      然后在你的刀片模板上。

      @foreach ($user->emails as $email) 
          {{ $email->email }}<br/>
      @endforeach
      

      查看Eager Loading 文档了解更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-30
        • 2019-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-22
        • 1970-01-01
        相关资源
        最近更新 更多