Laravel |重用查询变量而不是查询重复

时间:2018-02-13 09:39:27

标签: php mysql laravel reusability

我正在尝试重用一个查询变量,但看起来它最后指定的值不是原始值,这就是我的意思:

public class FooTableStorageComponent : TableStorageBase, IFooComponent
{
    private const string TableName = "foo";
    private const LocationMode ConsistencyMode = LocationMode.PrimaryOnly;

    public FooTableStorageComponent(string connectionString)
         : base(connectionString, TableName, ConsistencyMode)
    {
    }

    public GetFoo(string partitionKey, string rowKey)
    {
        var retrieveOperation = TableOperation.Retrieve<FooTableEntity>(partitionKey, rowkey)
        var tableEntity = (await Table.ExecuteAsync(
            retrieveOperation, 
            DefaultTableRequestOptions, 
            DefaultOperationContext)).Result as FooTableEntity;
        if (tableEntity != null && tableEntity.Timestamp > DateTime.Now.AddDays(-7))
        {
            return tableEntity.ToEntity();
        }
        else
        {
            var foo = CreateFoo(partitionKey, rowKey)
            var insertOperation = TableOperation.InsertOrMerge(FooTableEntity.From(foo));
            await Table.ExecuteAsync(insertOperation);
            return foo;
        }
    }
}

我想重复使用$categories = DB::table('invoice_detail') ->selectRaw('SUM(qty) as qty') ->where('loc_id', '=', $user->loc_id) ->join('items', 'invoice_detail.item_id', 'items.barcode') ->where('items.active', '1') ->join('categories', 'items.category_id', 'categories.id') ->addSelect('categories.name') ->groupBy('categories.name'); dump($categories->get()); //It returns whole products, which is OK. $topCategories = $categories->orderBy('qty', 'DESC')->take(5)->get(); dump($categories->get()); // It returns the top products, not the original value. $downCategories = $categories->orderBy('qty', 'ASC')->take(5)->get(); 变量来获取$categoriesTop Products,而不会重复查询。

但是在第一个转储中,它返回整个产品,这是正常的,然后在获得Down Products后,它返回顶级产品,而不是原始值。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

当且仅当该对象实施了__clone方法时,您始终可以使用__clone方法制作某个对象copy

$topCategories= clone $categories;
$topCategories->orderBy('qty', 'DESC')->take(5)->get();
$downCategories = clone $categories;
$downCategories->orderBy('qty', 'ASC')->take(5)->get();