Laravel отношения на столе с двумя типами флагов

У меня две таблицы

продуктов и пользователей

Оба этих объекта имеют связанные с ним изображения в таблице

изображений

Схема для таблицы изображений

id | image_id | resource_id | флаг

1 | 567575 | 1 | пользователь

2 | 423423 | 1 | продукт

Основываясь на этом флаге, я определяю, является ли его образ пользователя или образ продукта.

Если мне нужно будет загружать изображение пользователей, как это сделать?

Модель пользователя

<?php namespace App\Entities; use Illuminate\Database\Eloquent\Model; class User extends Model implements Transformable { use TransformableTrait; protected $table = 'users'; protected $primaryKey = 'users_id'; public function images() { return $this->hasMany('App\Entities\Image','resource_id'); } } 

Модель продукта

 <?php namespace App\Entities; use Illuminate\Database\Eloquent\Model; class Product extends Model implements Transformable { use TransformableTrait; protected $table = 'products'; protected $primaryKey = 'products_id'; public function images() { return $this->hasMany('App\Entities\Image','resource_id'); } } 

модель изображений

 <?php namespace App\Entities; use Illuminate\Database\Eloquent\Model; class Image extends Model implements Transformable { use TransformableTrait; protected $table = 'images'; protected $primaryKey = 'images_id'; public function products() { return $this->hasOne('App\Entities\Product','products_id'); } public function users() { return $this->hasOne('App\Entities\User','users_id'); } } 

Есть ли способ передать флаг в функции отношений images (), чтобы он извлекал запись на основе флагов?

Пожалуйста, помогите.

Вы можете попробовать это добавить условие в свой метод images() :

 <?php namespace App\Entities; use Illuminate\Database\Eloquent\Model; class User extends Model implements Transformable { use TransformableTrait; protected $table = 'users'; protected $primaryKey = 'users_id'; public function images($filtered=false) { if ($filtered) { return $this->hasMany('App\Entities\Image','resource_id')->where('flag','user'); } return $this->hasMany('App\Entities\Image','resource_id'); } } 

и попробуйте ту же логику для вашей модели Product

Измените модель изображения на:

 <?php namespace App\Entities; use Illuminate\Database\Eloquent\Model; class Image extends Model implements Transformable { use TransformableTrait; protected $table = 'images'; protected $primaryKey = 'images_id'; public function product() { return $this->belongsTo('App\Entities\Product', 'products_id', 'resource_id'); } public function user() { return $this->belongsTo('App\Entities\User', 'users_id', 'resource_id'); } } 

попробуйте следующим образом:

 $user_id = 1; $my_image= User::find($user_id)->images()->where('flag', '=', 'user')->first();