首页 > 解决方案 > laravel 与更多领域的关系

问题描述

我有这个用例我有一个包含 id、id_target、目标字段的附件表我通常通过加入 id_target 和 target 来使用它,例如

附加到 ON a.id_target = n 和 target = 'item' 的内部连接

是否可以将模型项中的关系与 item::with(attachment)->get() 一起使用?

非常感谢您

标签: phplaravel

解决方案


我的问题的解决方案非常基本。

我还不太明白他是如何使用关系的,然后我在查询日志中看到,关系是通过单独的查询而不是连接来管理的。

所以就我而言,这样做就足够了

    <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    protected $table = 'items';
    protected $primaryKey = 'id';
    protected $fillable = [
        'id','name','price'
    ];

    public function attachs() {
        return $this->hasMany('App\Models\Attach','id_target', 'id')->where('target','=','item');
    }
}

我在关系中连接 where 方法....

适合你的时代


推荐阅读