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

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

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
最佳答案

在 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 中文文档》 获取中间表字段

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

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

5年前 评论
你看我吊吗啊

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

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

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

5年前 评论
你看我吊吗啊

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

5年前 评论

在 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 中文文档》 获取中间表字段

5年前 评论

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