【问题标题】:How make a join table like bellow in laravel如何在 laravel 中制作像下面这样的连接表
【发布时间】:2021-03-10 20:54:57
【问题描述】:

你好,我想在 laravel 中的两个表之间进行连接,但是如果表 B 没有行查询返回 null。 我想要的是这样的。

table A

id user_id description
1    1      something
2    1       apple
3    2       cherry

table B

user_id post_id vote
(with no records initial)

result table

    id user_id description post_id  vote
    1    1      something    null   null
    2    1       apple       null   null
    3    2       cherry      null   null

我该怎么做? 在此先感谢您,对于英语变差我深表歉意。

【问题讨论】:

  • 在用户模型中建立 hasMany 关系。并获取 $user->posts

标签: mysql laravel join


【解决方案1】:

你应该使用leftJoin

 DB::table("tableA")->leftJoin("tableB","tableA.user_id",'=','tableB.user_id')
           ->select(["tableA.id as id",'tableA.user_id as user_id','description','post_id','vote'])->get();

【讨论】:

  • 谢谢,太完美了:D
【解决方案2】:

您可以利用雄辩的关系来获得所需的输出

Assume Table A is represented by ModelA and Table B is represented by ModelB

class ModelA extends Model
{
    //Get all related ModelB records
    public function kids()
    {
        return $this->hasMany(ModelB::class, 'user_id', 'user_id');
    }
}

class ModelB extends Model
{
    //Get the ModelA record to which the ModelB record belongs
    public function parent()
    {
        return $this->belongsTo(ModelA::class, 'user_id', 'user_id');
    }
}

现在您可以在任何地方获取 ModelA 记录的所有 ModelB(相关)记录


$modelA = ModelA::with('kids')->first();

$modelA->kids //These records will hold values from Table B

或者使用 QueryBuilder


$rows = DB::table('TableA')
    ->leftJoin('TableB', 'TableA.user_id', '=', 'TableB.user_id')
    ->select('id', 'TableA.user_id', 'description', 'post_id', 'vote');

Eloquent 或 Query Builder 是一种选择

【讨论】:

    【解决方案3】:

    假设表 A 是 User 模型,表 B 是 Post 模型。 雄辩的查询:

    $users = User::leftJoin('posts', function($join) {
          $join->on('users.id', '=', 'posts.user_id');
        })
        ->whereNull('posts.user_id')
        ->first([
            'users.id',
            'users.description',
            'posts.id',
            'posts.vote'
        ]);
    

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多