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 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制