如果我想取关系表中的其他字段该如何写?

比如我想获取关注时间 还有我增加一个字段秘密关注标记 如何设置和获取这个我自定义的字段

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

在 Model 中定义需要获取的关系表字段 created_at

class User extends Authenticatable
{
    .
    .
    .
    public function followers()
    {
        return $this->belongsToMany(User::class,'followers','user_id', 'follower_id')
                    ->withPivot('created_at')->withTimestamps();
    }

    public function followings()
    {
        return $this->belongsToMany(User::class,'followers','follower_id','user_id')
                    ->withPivot('created_at')->withTimestamps();
    }
    .
    .
    .
}

在 Controller 中使用 $follower->pivot->created_at 获取该字段的值

class UsersController extends Controller
{
    .
    .
    .
    public function followers(User $user)
    {
        $users = $user->followers()->paginate(30);
        foreach ($users as $follower) {
            //获取关系表的创建时间字段 赋值给$users->follow_time 供前台使用
            $follower->follow_time = $follower->pivot->created_at;
        }
        $title = '粉丝';
        return view('users.show_follow',compact('users','title'));
    }
    .
    .
    .
}

文档:模型关联《Laravel 5.6 中文文档》 获取中间表字段

7年前 评论
讨论数量: 7
你看我吊吗啊

先看文档再说话,文档里有查表的多种方式。

7年前 评论
你看我吊吗啊

@tooyond 是新手就不要这么暴躁,文档是说明书,告诉你如何调用laravel的函数,教程是实践,教你如何做出一个产品,两者都有存在的意义。你自己都说对文档不够熟悉,我让你去看文档的查表部分,你就去看

7年前 评论
leo
7年前 评论
你看我吊吗啊

连文档都懒得看的人,注定写不出好代码

7年前 评论
你看我吊吗啊

其实我没熟读 。。啥时候用啥时候查

7年前 评论

在 Model 中定义需要获取的关系表字段 created_at

class User extends Authenticatable
{
    .
    .
    .
    public function followers()
    {
        return $this->belongsToMany(User::class,'followers','user_id', 'follower_id')
                    ->withPivot('created_at')->withTimestamps();
    }

    public function followings()
    {
        return $this->belongsToMany(User::class,'followers','follower_id','user_id')
                    ->withPivot('created_at')->withTimestamps();
    }
    .
    .
    .
}

在 Controller 中使用 $follower->pivot->created_at 获取该字段的值

class UsersController extends Controller
{
    .
    .
    .
    public function followers(User $user)
    {
        $users = $user->followers()->paginate(30);
        foreach ($users as $follower) {
            //获取关系表的创建时间字段 赋值给$users->follow_time 供前台使用
            $follower->follow_time = $follower->pivot->created_at;
        }
        $title = '粉丝';
        return view('users.show_follow',compact('users','title'));
    }
    .
    .
    .
}

文档:模型关联《Laravel 5.6 中文文档》 获取中间表字段

7年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!