Laravel从关系和concat列创建简单的下拉列表

时间:2016-05-19 13:55:28

标签: php laravel

我想在2个表中创建简单的html代码中的下拉列表,它们具有单一的关系,在我的代码中,我无法将关系数据与其他表列连接起来。例如,这是我的代码:

$user_accounts = UserAccountNumber::with('currencyType')->select('*', DB::raw('CONCAT("CardNumber: ", card_number) AS account_info'))
            ->whereUserId(Auth::user()->id)
            ->pluck('account_info', 'id');

此代码工作正常,但我希望将currencyType表格列与UserAccountNumber表格对齐,并且我无法将tableName.columnName用于DB::raw()

例如:

$user_accounts = UserAccountNumber::with('currencyType')
    ->select(
        '*', 
        DB::raw('CONCAT(" CardNumber: ", card_number, "CurrencyType: ", currencyType.title) AS account_info'))
        ->whereUserId(Auth::user()->id)
->pluck('account_info', 'id');

然后我收到此错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'currencyType.currency_type' in 'field list' (SQL: select *, CONCAT("AccountNumber: ",account_number, " CardNumber: ", card_number, "CurrencyType: ", currencyType.currency_type) AS account_info from `user_account_numbers` where `user_id` = 17)
模型中的

currencyType方法:

public function currencyType()
{
    return $this->belongsTo(CurrencyType::class, 'currency_type', 'id');
}

1 个答案:

答案 0 :(得分:1)

Laravel不使用JOIN来建立关系,因此您必须为此编写特定查询。使用查询构建器。

这样的事情应该有效:

$user_accounts = DB::table('user_account_numbers')
    ->join('currencyType', 'user_account_numbers.currency_id', '=', 'currencyType.id')
    ->select('*', DB::raw('CONCAT(" CardNumber: ", card_number, "CurrencyType: ", currencyType.title) AS account_info'))
    ->whereUserId(Auth::user()->id)
    ->get();

我希望您能够理解并根据您的数据库架构进行调整。