Laravel关系在桌子上有两种类型的标志

时间:2016-01-28 09:28:05

标签: php mysql laravel laravel-5 eloquent

我有两张桌子

产品用户

这两个对象都有一个与表相关联的图像

图片

images表的架构是

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

请帮忙。

3 个答案:

答案 0 :(得分:3)

您可以尝试在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模型相同的逻辑

答案 1 :(得分:0)

将您的影像模型更改为:

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

答案 2 :(得分:0)

尝试这种方式:

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