【问题标题】:Model Relationship issue in LaravelLaravel 中的模型关系问题
【发布时间】:2019-12-24 02:23:03
【问题描述】:

我正在学习 Laravel 中的模型关系。我遇到以下问题:

我有一个主键为 NPI 的“NPIData”表

我有一个主键为 id 的“用户”表

我有一个包含两列的“UserToProviderMapping”表,一列用于 user_id(映射到 users 表上的 id),另一列用于 provider_npi(映射到 NPIData 表上的 NPI)。

我的控制器中有以下代码:

    public function index()
{
    //
    $user = Auth::id();
    $providers = UserToProviderMapping::where('user_id', $user)->get();

    return view ('my-health-hub', compact('providers'));
}

我目前在我的视图中有以下代码(显然不完整)

@foreach($providers as $provider)

 <li>{{$provider->provider_npi}}</li>

@endforeach

我不确定是否可以在此处使用模型关系,因为我在两个模型(用户和 NPIData)之间添加了另一个表。我正在尝试从 UserToProviderMapping 表中获取 provider_npi 并使用它来查找 NPIData 表中的数据并循环遍历。

【问题讨论】:

    标签: laravel


    【解决方案1】:

    Many-to-many relationship 就是你要找的东西:

    在您的User 模型上定义providers 方法,如下所示:

    class User extends Model
    {
        /**
         * The providers that belong to the user.
         */
        public function providers()
        {
            return $this->belongsToMany(
                'App\NPIData', 
                'user_to_provide_mappings', // the table name of the relationship's joining table (pivot table)
                'user_id',                  // the foreign key name of the model (on the pivot table) on which you are defining the relationship
                'provider_npi',             // the foreign key name of the model (on the pivot table) that you are joining to
                'id',                       // the primary key name of the model on which you are defining the relationship
                'NPI'                       // the primary key name of the model that you are joining to
            );
        }
    }
    

    然后在你的控制器上:

    use Illuminate\Http\Request;
    
    public function index(Request $request)
    {
        $providers = $request->user()->providers()->get();
    
        return view('my-health-hub', compact('providers'));
    }
    

    可选:您可以定义您的自定义中间模型UserToProviderMapping,如文档中所述:https://laravel.com/docs/master/eloquent-relationships#defining-custom-intermediate-table-models

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-08
      • 1970-01-01
      相关资源
      最近更新 更多