php - Laravel relationships on a table with two types of flags -


i have 2 tables

products , users

both of objects has images associated in table

images

the schema images table

id | image_id | resource_id | flag

1 | 567575 | 1 | user

2 | 423423 | 1 | product

based on flag identifying whether users image or whether products image.

if need eager load users image how do it?

user model

<?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');     } } 

product model

<?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');     } } 

images model

<?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');         }     } 

is there way can pass flag in relationship function of images() fetch record based on flags?

please out.

you can try adding conditional inside images() method:

<?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');     } } 

and try same logic product model


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -