31

クエリのを定義する方法はASありますか?

私は以下を試しました:

$data = News::order_by('news.id', 'desc')
    ->join('categories', 'news.category_id', '=', 'categories.id')
    ->left_join('users', 'news.user_id', '=', 'users.id') // ['created_by']
    ->left_join('users', 'news.modified_by', '=', 'users.id') // ['modified_by']
    ->paginate(30, array('news.title', 'categories.name as categories', 'users.name as username'));

問題は、['name']fromカテゴリがからのものに置き換えられることusersです。それらを異なる名前にする方法はありますか?

上記のエイリアスがある...両方の結合が返されるエイリアスを作成するにはどうすればよいusers.nameですか?

4

2 に答える 2

87

paginate()メソッドの2番目のパラメーターは、クエリで選択するテーブル列の配列を受け入れます。したがって、この部分:

paginate(30, array('news.title, category.name'));

このようにする必要があります:

paginate(30, array('news.title', 'category.name'));

更新 (質問を変更した後)

これを試して:

->paginate(30, array('news.title', 'categories.name as category_name', 'users.name as user_name'));

更新2 (質問を変更した後、もう一度)

テーブルでエイリアスを使用することもできます。

$data = News::order_by('news.id', 'desc')
    ->join('categories', 'news.category_id', '=', 'categories.id')
    ->join('users as u1', 'news.user_id', '=', 'u1.id') // ['created_by']
    ->join('users as u2', 'news.modified_by', '=', 'u2.id') // ['modified_by']
    ->paginate(30, array('news.title', 'categories.name as categories', 'u1.name as creater_username', 'u2.name as modifier_username'));
于 2013-01-14T14:24:40.490 に答える
4

この質問に対するより単純でわかりやすい答えは、Eloquentがテーブル名または列を使用してエイリアスを直接サポートすることを私が探していたものです。たとえば、次のようになります。

$users = DB::table('really_long_table_name AS t')
           ->select('t.id AS uid')
           ->get();
于 2019-06-12T12:19:01.003 に答える