具有两种类型的标志的表上的Laravel关系 [英] Laravel relationships on a table with two types of flags

查看:82
本文介绍了具有两种类型的标志的表上的Laravel关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个桌子

产品用户

这两个对象在表中都有与之关联的图像

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

图片

图像表的架构为

id | image_id | resource_id |标记

基于此标记,我正在确定它是用户图像还是产品图像.

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?

用户模型

<?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()的关系函数中传递一个标志,以便它根据标志来获取记录?

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?

请帮忙.

推荐答案

您可以尝试在images()方法内部添加条件:

You can try this adding a conditional inside your 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');
    }
}

并尝试与您的Product模型相同的逻辑

and try the same logic to your Product model

这篇关于具有两种类型的标志的表上的Laravel关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆