1
我有兩個表格。在laravel中使用Eloquent加入兩個模型5.3
用戶表:
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 | [email protected]| 12345 | 12345678 | | 6 | 5 |
| 6 | sara | [email protected]| 54321 | 87654321 | | 7 | 5 |
| 7 | joe | [email protected]| 56421 | 65875234 | | 7 | 8 |
| 8 | sag | [email protected]| 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();
但我想用雄辯。
,這是我用戶型號:
<?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');
}
}
我應該怎麼寫使用雄辯此查詢?我是否在模型中使用正確方法中的關係?我認爲我的模型應該被編輯,但我不知道如何。 感謝您的幫助。
您的解決方案和預期一樣。謝謝。 – rayan