2016-09-15 39 views
0

我想在laravel 5.2中使用agencies.organization_id = organizations.id获取具有组织表的外键的代理表。现在用户表也有组织表使用users.organization_id = organizations.id的外键。现在如何获取哪些代理机构与users_id链接的代理机构表。collection to laravel中的字符串5.2查询生成器

public function postagency(Request $request) { 
     $user_id = $request->user_id; 
     $org_id = User::where('id', $user_id)->pluck('organization_id')->first(); 
     $postagencies = agency::where('organization_id', $org_id); 
     echo $postagencies; 
    } 

回答

1

据我所知,用户只能在一个组织下,而一个组织有许多代理机构。如果不是这样,我会改变我的答案。

首先在你的模型中设置你的关系。一个例子是:

// User.php 

public function organization() 
{ 

    return $this->belongsTo('App\Organization'); // App\Organization can be changed depending on the used namespace 

} 

更多信息可查询here。如果你需要更多的例子,请问。

您已经创建了这些关系后,你可以检索你的机构是这样的:

$user= User::find($request->user_id); 

if (!$user) ... // Check if user exists 

$agencies = $user->organisation->agencies; 

如果我需要更详细说明事情就问。希望这有助于:)

+0

感谢它的工作..在organization.php中添加一个hasmany()relatioship ... :) –