【发布时间】:2017-03-11 08:04:09
【问题描述】:
我有两张桌子。
用户表:
id (integer)
name (string)
email (string)
phone (string)
codeMeli (string)
和user_admin表:
userId (integer)
adminId (integer)
注意:adminid 字段保留作为另一个用户管理员的用户 ID。一个用户可以是多个用户的管理员,或者一个用户可能有多个管理员。例如:
| id | name | email | phone | codeMeli | | userid | adminid |
---- ------ ------- ------- ---------- -------- ---------
| 5 | mike | m@yaho| 12345 | 12345678 | | 6 | 5 |
| 6 | sara | s@yaho| 54321 | 87654321 | | 7 | 5 |
| 7 | joe | j@yaho| 56421 | 65875234 | | 7 | 8 |
| 8 | sag | s@yaho| 57635 | 64616843 |
我使用 OueryBuilder 尝试了这个查询并且效果很好:
Users::select('id','name','email','codeMeli','phone')
->join('user_admin','user_admin.userid','=','users.id')
->whereRaw("name LIKE '%".$name."%' and email LIKE '%".$email."%' and codeMeli LIKE '%".$codeMeli."%' and phone LIKE '%".$phone."%' and user_admin.adminid=".$CurrentUSerID)
->get();
但我想使用 Eloquent。
这是我的用户模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Users extends Model
{
protected $table = 'users';
public $timestamps = false;
protected $fillable = ['name','phone','email','codeMeli','admin'];
public function userAdmin()
{
return $this->belongsToMany('App\UserAdmin','id','userid');
}
}
和user_admin型号:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserAdmin extends Model
{
protected $table = 'user_admin';
public $timestamps = false;
protected $fillable = ['userid','adminid'];
public function users()
{
return $this->belongsToMany('App\Users','id','adminid');
}
}
我应该如何使用 Eloquent 编写这个查询?我是否在模型中以正确的方法使用关系?我认为我的模型应该被编辑,但我不知道如何。 感谢您的帮助。
【问题讨论】:
标签: model eloquent relationship laravel-5.3