【问题标题】:Laravel Order Eloquent by relationLaravel Order Eloquent 按关系
【发布时间】:2017-12-21 09:23:38
【问题描述】:

对于一个新项目,我正在一家网上商店工作。我的产品与工厂细节有一对多的关系。工厂详细信息有一个列价格。我需要以第一个细节的价格订购产品。

如果我使用连接,我会按价格订购所有产品,但我会为每个详细关系获得一个新产品。

我试过了:

$products = $products->get(); 
$products = $products->sortBy(function ($product, $key) { 
    return $product->plantDetails()->first()->price; }); 
    $products = $this->paginate($products, $perPage = 24, true);
}

$this->paginate 是:

public function paginate($items, $perPage = 15, $page = null, $options = []) { 
    $page = $page ?: (Paginator::resolveCurrentPage() ?: 1); 
    $items = $items instanceof Collection ? $items : Collection::make($items); 
    return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options); 
}

但是我没有在分页链接中获得当前页面。有人有什么想法吗?

【问题讨论】:

  • 你的意思是,当前页面从方法到渲染分页的链接像$products->render()只显示什么,但其他页面显示像http://site.test/products?page=2这样的东西?
  • $products->links() 按预期呈现分页,但 site.test/products 页面上的链接将是 site.dev/?page=2
  • 您是否尝试删除paginate 上的第三个参数?还是手动设置分页器的路径? $this->paginate($products, 24)->setPath($request->url());
  • 周二早上第一件事要试试
  • $this->paginate($products, 24)->setPath($request->url());工作。谢谢

标签: laravel eloquent


【解决方案1】:

如果你使用类似的东西会怎样:

$products = $products->sortBy(function ($product, $key) { 
    return $product->plantDetails()->first()->price; })->paginate(24)

Paginate 也将执行此操作... 但我不明白您所说的“需要以第一个细节的价格订购产品?”

first() 将返回来自 plantDetails 的第一个对象,而 first()->price price 将准确返回该对象的 price 属性。

如果您使用查询构建器中的连接方法,那么您不需要使用 eloquent 关系 ..

可能是这样的:

$products = DB::table('products')->
join('plantDetails','key','=','key') ->sortBy('price')->paginate(24);

其中 key 是 products 和 plantDetails 之间的公共列。

希望对你有帮助,

【讨论】:

  • $products = $products->orderBy(function ($product, $key) { return $product->plantDetails()->first()->price; })->paginate(24 ) 我得到 strtolower() 期望参数 1 是字符串,对象给定错误。它在 paginate() 或 get() 上给出了这个错误。当我删除分页时,我得到一个构建器对象。当我在对象上使用 count() 时,我得到了正确数量的项目
猜你喜欢
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 2016-10-15
  • 1970-01-01
  • 2014-01-15
  • 2021-01-25
  • 2014-06-25
  • 2015-03-02
相关资源
最近更新 更多