首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何用百拉威制作一张像吼叫的接合桌

如何用百拉威制作一张像吼叫的接合桌
EN

Stack Overflow用户
提问于 2020-11-28 09:22:36
回答 3查看 38关注 0票数 0

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

代码语言:javascript
运行
复制
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

我怎么能这么做?事先谢谢你,我为英语不好而道歉。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-11-28 09:30:20

你应该使用leftJoin

代码语言:javascript
运行
复制
 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();
票数 1
EN

Stack Overflow用户

发布于 2020-11-28 09:33:20

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

代码语言:javascript
运行
复制
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记录的所有ModelA(相关)记录。

代码语言:javascript
运行
复制
$modelA = ModelA::with('kids')->first();

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

或者使用QueryBuilder

代码语言:javascript
运行
复制
$rows = DB::table('TableA')
    ->leftJoin('TableB', 'TableA.user_id', '=', 'TableB.user_id')
    ->select('id', 'TableA.user_id', 'description', 'post_id', 'vote');

雄辩或查询生成器是一种选择

票数 0
EN

Stack Overflow用户

发布于 2020-11-28 09:50:41

假设表A是用户模型,表B是Post模型。雄辩的质疑:

代码语言:javascript
运行
复制
$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'
    ]);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65048096

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档