Laravel 5.1: handle joins with same column names

前端 未结 4 1862
傲寒
傲寒 2021-02-04 00:00

I\'m trying to fetch following things from the database:

  • user name
  • user avatar_name
  • user avatar_filetype
  • complete conversation_messages<
相关标签:
4条回答
  • 2021-02-04 00:29

    Take a look at this example of trying to join three tables staffs, customers and bookings(pivot table).

     $bookings = \DB::table('bookings')
            ->join('staffs', 'staffs.id' , '=', 'bookings.staff_id')
            ->join('customers', 'customers.id' , '=', 'bookings.customer_id')
            ->select('bookings.id', 'bookings.start_time',  'bookings.end_time', 'bookings.service', 'staffs.name as Staff-Name',  'customers.name as Customer-Name')
            ->orderBy('customers.name', 'desc')
            ->get();
        return view('booking.index')
                ->with('bookings', $bookings);
    
    0 讨论(0)
  • 2021-02-04 00:39

    I had the following problem, simplified example:

    $result = Donation::join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello@papabello.com')->first();
    

    $result is a collection of Donation models. BUT CAREFUL:

    both tables, have a 'created_at' column. Now which created_at is displayed when doing $result->created_at ? i don't know. It seems that eloquent is doing an implicit select * when doing a join, returning models Donation but with additional attributes. created_at seems random. So what I really wanted, is a return of all Donation models of the user with email hello@papabello.com

    solution is this:

    $result = Donation::select('donation.*')->join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello@papabello.com')->first();
    
    0 讨论(0)
  • 2021-02-04 00:39

    Yeah, simply rename the column on either table and it should work. Also what you can do is, rename the user.name column to anything, also rename sender column of conversation_messages to id and perform a natural join.

    0 讨论(0)
  • 2021-02-04 00:44

    Meh okay.. i've found a simple solution here

    ->select('users.name as userName', 'conversation_messages.*', 'user_avatars.name as avatarName', 'user_avatars.filetype')
    

    As you can mention I've added the requested "as-Feature" next to the table.columnName

    0 讨论(0)
提交回复
热议问题