【问题标题】:how to make a relation in laravel in model?如何在模型中的laravel中建立关系?
【发布时间】:2021-03-23 03:28:09
【问题描述】:

我在 db 中有 2 个表

1) Orders它的模型是Order

2) Ordertakers它的模型是Ordertaker

每个订单都是由接单员创建的,我想按ot_id 计算订单数量,有点像这种情况

Order::where('ot_customer_distance', '<' , 50)->where('ot_id', $id)->get();

所以在模型中我使用了这个

class Ordertaker extends Model
{   
    public function vistorders(){
        return $this->belongsTo('App\Order','ot_id')->where('ot_customer_distance', '<' , 50)->count();
    }
}

我的控制器是

public function index()
    {
        $ids = [Auth::id()];
        if (Auth::user()->role < 3) {
            $ids = array_merge($ids, User::where('ot_of', Auth::id())->pluck('id')->toArray());
        }
        $ordertaker = User::where('role', 5)->has('ordertaker')->with('ordertaker');
        $ordertaker = $ordertaker->where('ot_of', Auth::id());
        $ordertaker = $ordertaker->get();
        return view('all_ordertakers', compact('ordertaker'));
     
    }

我的刀是

@foreach($ordertaker as $ot)
<td><b>Total Vst</b><br>{{ sizeof($ot->vistorders) }}</td>
@endforeach

但我的结果是 0 有什么帮助吗?

【问题讨论】:

    标签: php laravel model-view-controller eloquent relationship


    【解决方案1】:

    如果要通过ot_id来统计订单数量,那么关系必须定义不同。一个OrderTaker有很多Orders,它不属于一个订单。此外,不应在关系中定义 where 和 count 查询。

    public function vistorders(){
            return $this->hasMany('App\Order','ot_id');
    }
    

    现在引用$ot-&gt;vistorders 将返回订单接受者Orders 的雄辩集合。因此,您可以使用$ot-&gt;vistorders-&gt;count() 获取完整计数。调用 $ot-&gt;vistorders() 将返回查询生成器,如果需要该值,您可以调用 $ot-&gt;vistorders()-&gt;where('ot_customer_distance', '&lt;' , 50)-&gt;count()

    此外,您急于在此处加载 ordertaker 关系:

    $ordertaker = User::where('role', 5)->has('ordertaker')->with('ordertaker');
    

    您还可以更进一步,使用点语法来预先加载visitorders

    $ordertaker = User::where('role', 5)->has('ordertaker')->with('ordertaker.visitorders');
    

    【讨论】:

      【解决方案2】:

      您的代码中有两个问题。

      1. 您正在使用急切/延迟加载,但调用的是类名而不是关系/函数名。先更正一下。
      2. 无法对关系执行 where 条件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-14
        • 2015-01-20
        • 1970-01-01
        • 2011-12-01
        • 2021-12-17
        相关资源
        最近更新 更多