Laravel按相关表格排序

时间:2016-04-26 06:30:50

标签: php laravel sorting html-table

我的项目中有产品和类别模型。产品属于Category。由于Product有外键category_id,我可以轻松地对输出进行排序:

import UIKit
import XCPlayground

let view = UIView(frame: CGRectMake(0, 0, 400, 400))
view.backgroundColor = .whiteColor()
let mover = UIView(frame: CGRectMake(0, 0, 10, 10))
mover.backgroundColor = .redColor()
view.addSubview(mover)
XCPlaygroundPage.currentPage.liveView = view

let animation = CAKeyframeAnimation(keyPath: "position")
let path = UIBezierPath(arcCenter: CGPointMake(200, 200), radius: 160, startAngle: 1, endAngle: 5, clockwise: true)
animation.path = path.CGPath
animation.duration = 2
animation.calculationMode = kCAAnimationPaced
mover.layer.addAnimation(animation, forKey: "position")
mover.center = path.currentPoint

但我真正想要的是按类别名称对产品进行排序,所以我尝试了:

$products = Product::orderBy('category_id', 'asc')->get();

但这没有任何结果。作为测试,我已经返回$products = Product::with(['categories' => function($q){ $q->orderBy('name', 'asc')->first(); }]); 并且输出正常......

这是雄辩的关系。

产品

return Product::with('categories')->first();

分类

class Product extends Model
{
    protected $fillable = [
        'name',
        'description',
        'price',
        'category_id',
    ];

    protected $hidden = [
        'created_at',
        'updated_at',
    ];

    public function categories()
    {
        return $this->belongsTo('\App\Category', 'category_id');
    }
}

观点部分:

class Category extends Model
{
    protected $fillable = [
        'name'
    ];

    public function products()
    {
        return $this->hasMany('\App\Product');
    }
}

4 个答案:

答案 0 :(得分:6)

我没有对此进行过测试,但我认为这应该可行

Sub Macro2()
'
' Macro2 Macro
'
    Dim FileName As String
    Dim FileName2 As String

    FileName = Sheet1.TextBox1.Text
    FileName2 = "C:\TEMP\" & FileName & "\"

    MsgBox (FileName2)
    MkDir (FileName2)

    ChDir (FileName2)

    ActiveWorkbook.SaveAs FileName:=FileName2 & FileName & "2xlsm.xlsm", _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
        FileName2 & FileName & "_2xlsm.pdf", Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
        True
End Sub

这也应该有效:

// Get all the products
$products = \App\Product::all();

// Add Closure function to the sortBy method, to sort by the name of the category
$products->sortBy(function($product) { 
  return $product->categories()->name;
});

答案 1 :(得分:3)

您可以使用join(),尝试以下代码

$query = new Product; //new object
//$query = Product::where('id','!=',0);
$query = $query->join('categories', 'categories.id','=','products.categories.id');
$query = $query->select('categories.name as cat_name','products.*');
$query = $query->orderBy('cat_name','asc');
$record = $query->get();

答案 2 :(得分:0)

您只需向Eloquent紧急加载提供函数,即可在其中处理如何查询相关表。

$product = Product::with(['categories' => function ($q) {
  $q->orderBy('name', 'asc');
}])->find($productId);

答案 3 :(得分:-1)

在laravel中,你无法通过相关表执行订单而无需手动加入相关表格,这真的很尴尬,但这可以包装可以为您提供开箱即用的https://github.com/fico7489/laravel-eloquent-join