laravel 5.1 eloquent select 带有前缀连接表

标签 laravel select eloquent prefix

我有这个查询

$sales = Sales::join('customer', 'customer.id', '=', 'sales.customer_id')
->join('cashier', 'cashier.id', '=', 'sales.cashier_id')
->first();

我如何选择带有前缀的每个表,以便我可以这样调用:
  • $order->customer_name
  • $订单->收银员姓名

  • 通过上面的查询,我只得到一个名称行,因为每个表都有相同的列名 name , 什么
    我想要的是在我称之为 customer_ 的每个表中添加前缀, cashier_ , sales_
    更新

    我期望的结果是这样的
    customer_name
    customer_address
    customer_phone
    cashier_name
    cashier_another_column
    cashier_another_column2
    sales_date
    sales_another_column
    sales_another_column2
    

    最佳答案

    答案是你不能那样做。我通常只使用相同的列名作为别名,其余的则使用 * .所以您需要为所有相同的列名设置别名以解决冲突

    Sales::join('customer', 'customer.id', '=', 'sales.customer_id')
    ->join('cashier', 'cashier.id', '=', 'sales.cashier_id')
    ->select(['*', 'customer.name as customer_name', 'cashier.name as cashier_name'])
    ->get();
    

    关于laravel 5.1 eloquent select 带有前缀连接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37650183/

    相关文章:

    mysql - Laravel Eloquent Where 条件来自 2 个表

    php - 在线商店订单管理的数据库逻辑

    postgresql - 基于选择列内容的动态连接(postgres)

    oracle - oracle中select中的序列和大小写

    jquery - 如何在 Rails 4/jQuery 中创建链式选择?

    laravel - 为什么 eloquent 中的模型名称与表名称不同?

    laravel-5 - 拉拉维尔 5 : Return all fields except created_at and udpated_at

    php - Laravel 5 View语法错误

    Laravel 自定义验证

    php - 为什么 laravel View 显示空白页?