php - Laravel Eloquent - 如何加入表格

标签 php laravel laravel-5 eloquent

我正在为我的应用开发 API。

我正在尝试从数据库中提取项目并将它们返回到 JSON 对象中, 我的项目表如下所示:

Items
-id
-name
-description
-price
-currency_id
-company_id

这是我获取元素的方式:

$rows = Company::where('guid',$guid)
                ->first()
                ->items()
                ->orderBy('name', $sort_order);

我想用包含货币表所有列的货币对象替换 currency_id

所以我的结果会是这样的:

[
  {
    'id':'1',
    'name':'name',
    'description': 'example',
    'price':'100',
    'currency':{
     'id':'1',
     'name':'usd',
     'symbol': '$'
     }
  }
]

更新: 这是我的货币表:

id
name
symbol
code

最佳答案

编辑 2:用户的问题比这更复杂,因为分页和搜索与查询集成。帮助 https://pastebin.com/ppRH3eyx

编辑:我已经测试了代码。所以在这里。

在公司模型中

public function items()
{
    return $this->hasMany(Item::class);
}

在项目模型中

public function currency()
{
    return $this->belongsTo(Currency::class);
}

Controller 逻辑

$items = Company::with(['items' => function($query) use ($sort_order) {
    $query->with('currency')->orderBy('name', $sort_order);
}])
    ->where('guid', $guid)
    ->first()
    ->items;

带有测试数据的结果

[
    {
        "id": 2,
        "name": "Toy",
        "description": "Random text 2",
        "price": 150,
        "company_id": 1,
        "currency_id": 1,
        "currency": {
            "id": 1,
            "name": "usd",
            "symbol": "$",
            "code": "USD"
        }
    },
    {
        "id": 1,
        "name": "Phone",
        "description": "Random text",
        "price": 100,
        "company_id": 1,
        "currency_id": 1,
        "currency": {
            "id": 1,
            "name": "usd",
            "symbol": "$",
            "code": "USD"
        }
    }
]

试试这个。

$rows = Company::with('items.currency')
    ->where('guid', $guid)
    ->first()
    ->items()
    ->orderBy('name', $sort_order);

关于php - Laravel Eloquent - 如何加入表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44062386/

相关文章:

php - 如何使用 php 从 HTML 表单中读取非输入相关的文本?

Laravel:未定义身份验证用户提供程序 []

javascript - JS加入购物车

php - Cakephp 和 Laravel 共存

laravel - 在 Laravel 5 Controller 中找不到类 'App\Http\Controllers\DB'

laravel - 响应 header 名称 'Access-Control-Allow-Origin ' 包含无效字符,中止请求

php - 通过电子邮件询问评级

php - 以小时和分钟计算两个日期之间的差异

php - 嵌套实体中的 Doctrine EntityManager clear 方法

mysql - 如何在急切加载模型中使用 groupBy?