【问题标题】:Laravel: user defined object name in Join QueryLaravel:加入查询中用户定义的对象名称
【发布时间】:2014-12-13 11:26:06
【问题描述】:

我有一个用 Laravel 编写的成功返回的连接查询。我现在正在尝试将对象名称添加到返回的值中,就好像它是从表中返回的一样。

Laravel 查询

$post = DB::table('follow')
    ->join('posts', 'follow.user2', '=', 'posts.userid')
    ->where('follow.user1',Auth::user()->id)
    ->where('follow.user2','!=',Auth::user()->id)
    ->where('posts.created_at','>',$update)
    ->select('posts.created_at', 'posts.userid')
    ->orderBy('posts.created_at','desc')
    ->get();

以上查询返回以下内容

array (size=1)
0 => 
  object(stdClass)[208]
    public 'created_at' => int 1418466963
    public 'userid' => int 5

我想要实现的是以下输出

array (size=1)
0 => 
  object(stdClass)[208]
    public 'created_at' => int 1418466963
    public 'userid' => int 5
    public 'oType' => string 'post'  //This is user defined.

我尝试的是(显然是错误的,但只是暗示我在尝试什么)

$post = DB::table('follow')
    ->join('posts', 'follow.user2', '=', 'posts.userid')
    ->where('follow.user1',Auth::user()->id)
    ->where('follow.user2','!=',Auth::user()->id)
    ->where('posts.created_at','>',$update)
    ->select('posts.created_at', 'posts.userid', 'oType as post') //Compare this line with 1st query
    ->orderBy('posts.created_at','desc')
    ->get();

【问题讨论】:

    标签: php mysql laravel-4


    【解决方案1】:

    您可以通过使用 DB::raw() 来实现此目的。

    ->select('posts.created_at', 'posts.userid', DB::raw('\'post\' as oType'))
    

    【讨论】:

    • Laravel 在DB:raw('\'post\' as oType') 处抛出错误syntax error, unexpected ':'
    • 抱歉,应该是 DB::raw,而不是 DB:raw。更正答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    相关资源
    最近更新 更多