我有一個分貝三個表,內容如下(並非所有列,但最小爲清楚起見):如何正確設置數據透視表中Laravel雄辯的關係5.2
admins (id, community_id, email, password, level)
community (community_id, community_name)
community_results (community_result_id, community_session_id)
community_sessions (community_session_id, community_id)
我已經安裝了關聯的模型和我的管理員控制器中我有以下代碼,簡單地將數據庫中的所有結果捕獲到laravel集合中(並且工作正常)。 管理員表包含兩種類型的管理員用戶 - 一個是可訪問數據庫中每一行的「超級用戶」,另一種是「社區管理員」,並且只能訪問其社區結果(由管理員表中的級別列)。
以「社區管理員」身份登錄到管理員時,我只想爲他們的社區獲取結果(admins.community_id是此實例中將此管理員關聯到社區的外鍵)。
例如,John Doe是'ACME社區'的'社區管理員',屬於community_id 5,登錄時他只會獲得與該特定相關的所有'社區會話'的'社區結果'社區(community_id是community_sessions表中的外鍵)。
所以我需要找到一種方法來創建CommunitySession.php模型中results()關係的修改版本,而不是查詢EVERY行只檢索一個或多個community_session_id的那些 - 或者有辦法使用該Community.php模型來創建一個關係到使用如下的關係,結果基本拉...
$community = Community::find(5);
$community->results; // pull results for this community using a relation
任何人都可以提出來做到這一點的最好方法是什麼?由於事先
class AdminResultController extends Controller
{
public function index()
{
// if logged in as the 'superuser' admin get ALL results
if (Auth::guard('admin')->user()->level == 1)
{
$results = CommunityResult::all();
} else {
// logged in as 'standard' admin get only their community results
$results = new CommunityResult;
// how do I get collection of results for this community only
}
}
}
// CommunityResult.php(模型)
class CommunityResult extends Model
{
public $primaryKey = 'community_result_id';
public function session()
{
return $this->hasOne('App\CommunitySession', 'community_session_id', 'community_session_id');
}
}
// CommunitySession.php(模型)
class CommunitySession extends Model
{
public $primaryKey = 'community_session_id';
public function community()
{
return $this->belongsTo('App\Community', 'community_id');
}
public function results()
{
return $this->hasMany('App\CommunityResult', 'community_session_id');
}
}
// Community.php(模型)
class Community extends Model
{
public $table = 'community';
public $primaryKey = 'community_id';
public function sessions()
{
return $this->hasMany('App\CommunitySession', 'community_id');
}
}
如何使用該行代碼? – Zabs
在with()方法中,您可以獲取與該對象相關的數據,首先您必須獲取已登錄的用戶對象,然後使用雄辯的方法與該用戶獲取相關數據 – yashan