dongsunny1113 2018-06-08 15:18
浏览 28
已采纳

Laravel:无法加入表格

I am trying to join two tabels using Laravel (just started using it). One table holds user information, and the other table holds a users friend IDs.

So one user can have multiple friends. I have done this is the user class:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table="user_info";

    public function getFriends()
    {
        //user_id is the column in the user_friends table that should be linked to the id table in this class table (user_info)

        return $this->hasMany('App\UserFriends','user_id','id');
    }
}

And the other class (UserFriends)

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserFriends extends Model
{
    protected $table="user_friends";
}

Then in a controller I call

$t = $this->sql_obj->getFriends()->toSql();

However, if I print the result of this it returns this:

select * from `user_friends` where `user_friends`.`user_id` is null and `user_friends`.`user_id` is not null

Why is it not joining the tables?

Thanks for any help!

  • 写回答

1条回答 默认 最新

  • douli1872 2018-06-08 15:34
    关注

    in Your UserModel :

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class User extends Model
    {
        protected $table="user_info";
    
        public function getFriends()
        {
           return $this->belongsToMany('App\User', 'user_friends', 'user_id', 'id');
        }
    }
    

    in your controller :

    if you want to get Auth user's friend :

     public function friends(Request $request){
    
          $friends = Auth::user()->getFriends;
          return response()->json(array('friends'=>$friends));   
    
     }
    

    if you want to get other user's friends :

      public function friends(Request $request){
          $userid=$request->input('userid');
          $user=User::find($userid);
          $friends = $user->getFriends;
          return response()->json(array('friends'=>$friends));   
     }
    

    or If you want to use query builder to join :

       use DB;
    
     public function friends(Request $request){
        $userid=$request->input('userid');  // Auth::user()->id
    
        $friends= DB::table('user_info')
        ->join('user_friends', 'user_info.id', '=', 'user_friends.user_id')
        ->where('user_friends.user_id', '=',$userid)         
        ->select('user_info.*')
        ->get();
    
        return response()->json(array('friends'=>$friends));   
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件