【问题标题】:remove global scope from relation in laravel从 laravel 中的关系中删除全局范围
【发布时间】:2019-03-29 22:11:05
【问题描述】:

7 项目 我拥有Voucher_detale 模型的全局范围

<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class getVouchers implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('vouchers_detale_state', '=', 1);
    }
}

我有Voucher 模型,里面有很多这是代码'

public function getDetales()
{
    return $this->hasMany('App\Vouchers_detale','vouchers_detale_voucher_id','id')->withTrashed();
}

在刀片里面我有这个代码

@foreach($voucher['getDetales'] as $v)
<tr class='table-warning'>
    <td>
        <a href='/{{$path}}/Vouchers_detales/{{$v["id"]}}'>{{$v['vouchers_detale_user_id']}}</a>

        <div class='selected d-print-none'>
            @foreach($v->getUpdate as $update)
                <span style='color:black'>{{$update['update_history_old_amount']}}</span>
                {{$update['created_at']}}
                {{$update['getUserData']['user_name']}}
                <hr />
            @endforeach
        </div>
    </td>
    <td>{{$v['getUserData']['user_name']}}</td>
    @if($v['vouchers_detale_amount'] > 0)
        <td>{{$v['vouchers_detale_amount']}}</td>
        <td></td>
        @php $total_debt +=  $v['vouchers_detale_amount'] @endphp
    @else
        <td></td>
        <td>{{$v['vouchers_detale_amount'] * -1}}</td>
        @php $total_credit += $v['vouchers_detale_amount'] * -1 @endphp
    @endif
    <td>{{$v['vouchers_detale_desc']}}</td>
</tr>
@endforeach

现在我如何忽略我尝试过的 foreach 中的全局范围

@foreach($voucher['getDetales']->withoutGlobalScopes() as $v)

我遇到了这个错误

Method Illuminate\Database\Eloquent\Collection::withoutGlobalScopes does not exist.

我如何忽略来自 foreach 关系的全局范围 谢谢

【问题讨论】:

    标签: php laravel scope model


    【解决方案1】:

    没关系,我刚刚创建了一个新关系

    public function getDetalesWithout()
    {
        return $this->hasMany('App\Vouchers_detale','vouchers_detale_voucher_id','id')->withTrashed()->withoutGlobalScope('App\Scopes\getVouchers');
    }
    

    谢谢

    【讨论】:

    • 这当然可以,但我只是想知道是否有办法在现有的关系上动态地做到这一点
    • 对我来说只适用于没有 withTrashed。在 hasMany 之后直接使用 withoutGlobalScope。
    猜你喜欢
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 2015-11-24
    • 2016-04-14
    • 2017-05-30
    • 2015-07-06
    • 1970-01-01
    相关资源
    最近更新 更多