Laravel 5.2。使用雄辩关系创建复杂查询

时间:2017-03-03 16:37:51

标签: php mysql laravel laravel-5.2 laravel-eloquent

我有几张桌子,想要加入他们,使用雄辩的关系,但我不知道如何。

包含所有表格的图片:

all tables

第一个表(Leads)使用关系:

与表sphere_attributes连接

leads.sphere_id = sphere_attributes.sphere_id

从这个关系我想得到列“标签”。

theese标签的值存储在另一个表“sphere_attribute_options”的“value”列中。

Leads与sphere_attribute_options相关:

    leads.sphere_id = sphere_attributes.sphere_id
    sphere_attributes.id = sphere_attribute_options.sphere_attr_id
    AND sphere_attribute_options.ctype=’agent’

我只需要来自sphere_attribute_options的值,其中表sphere_bitmask_XX(XX = sphere_id)的字段fb_AID_OID = 1(AID = sphere_attributes.id,OID = sphere_attribute_options.id)。

sphere_bitmask_XXleads之间的关系:

sphere_bitmask_XX.user_id = leads.id AND sphere_bitmask_XX.type ='lead'

我的模特:

namespace App\Models;

use Cartalyst\Sentinel\Users\EloquentUser;

class Lead extends EloquentUser
{

    protected $table = "leads";

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'agent_id', 'sphere_id',
    ];


    public function sphere()
    {
        return $this->hasOne('App\Models\Sphere', 'id', 'sphere_id');
    }

    public function labels()
    {
        return $this->hasMany('App\Models\SphereAttr', 'sphere_id', 'sphere_id');
    }
}

SphereAttrOptions

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class SphereAttrOptions extends Model
{
    protected $table = 'sphere_attribute_options';

    protected $fillable = ['sphere_attr_id', 'ctype', '_type', 'name', 'value', 'icon', 'position'];

    public function attribute()
    {
        return $this->belongsTo('App\Models\SphereAttr', 'id', 'sphere_attr_id');
    }
}

SphereAttr

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class SphereAttr extends Model
{
    protected $table = 'sphere_attributes';
    protected $fillable = ['_type', 'label', 'icon', 'required', 'position'];

    public function options()
    {
        return $this->hasMany('App\Models\SphereAttrOptions', 'sphere_attr_id', 'id')
            ->where('ctype', '=', 'agent')->orderBy('position');
    }

    public function sphere()
    {
        return $this->belongsTo('App\Models\Sphere', 'id', 'sphere_id');
    }

}

SphereMask

namespace App\Models;

use DB;
use Illuminate\Database\Eloquent\Model;

class SphereMask extends Model
{

}

0 个答案:

没有答案