jeudi 28 janvier 2016

Laravel relationships on a table with two types of flags

I have two tables

products and users

Both of this objects has images associated with it in a table

images

The schema for the images table is

id | image_id | resource_id | flag

1 | 567575 | 1 | user

2 | 423423 | 1 | product

Based on this flag i am identifying whether its a users image or whether its a products image.

If I need to eager load a users image how do it 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');
    }
}

Is there a way I can pass a flag in the relationship function of images() so that it will fetch the record based on the flags?

Please help out.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire