【问题标题】:collection to string in laravel 5.2 query builderlaravel 5.2查询生成器中的集合到字符串
【发布时间】:2016-09-15 18:48:58
【问题描述】:

我想在 laravel 5.2 中进行查询,以使用机构.organization_id=organizations.id 获取具有组织表外键的机构表。现在用户表也有外键和组织表使用 users.organization_id=organizations.id。现在如何获取与 users_id 链接的机构表。

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;
    }

【问题讨论】:

    标签: php laravel laravel-5.2


    【解决方案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;
    

    如果我需要更详细地解释事情,请询问。希望这会有所帮助:)

    【讨论】:

    • 谢谢它的工作.. 在 organization.php 中添加一个 hasmany() 关系... :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 2020-10-19
    • 2017-01-30
    • 2016-08-28
    相关资源
    最近更新 更多