为什么是 $reply->topic->increment ('reply_count', 1) 而不是 $reply->topic ()->increment ('reply_count', 1)?

我觉得在模型里面定义了关联函数topic(),,,所以为什么不是topic(),,而是topic

followyounger
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
最佳答案

$reply->topic()->increment('reply_count', 1) 我认为这种方式更好,这个只会进行一次数据库更新操作,如果是 $reply->topic->increment('reply_count', 1),会先将模型取出,然后再进行更新操作。

这个是 $reply->topic->increment('reply_count', 1) 查找方式:

file

这个是 $reply->topic()->increment('reply_count', 1) 查找方式:

file

5年前 评论
讨论数量: 12

$reply->topic == $reply->topic()->get()
这么样会不会好理解一些

5年前 评论
oOops 3年前

$reply->topic()->increment('reply_count', 1) 我认为这种方式更好,这个只会进行一次数据库更新操作,如果是 $reply->topic->increment('reply_count', 1),会先将模型取出,然后再进行更新操作。

这个是 $reply->topic->increment('reply_count', 1) 查找方式:

file

这个是 $reply->topic()->increment('reply_count', 1) 查找方式:

file

5年前 评论

@hustnzj

\DB::enableQueryLog();

// 这里写查询

dd(\DB::getQueryLog());
5年前 评论

$reply->topic == $reply->topic()->get()
这么样会不会好理解一些

5年前 评论
oOops 3年前
followyounger

@Ken 谢谢你啊

5年前 评论

$reply->topic()->increment('reply_count', 1) 我认为这种方式更好,这个只会进行一次数据库更新操作,如果是 $reply->topic->increment('reply_count', 1),会先将模型取出,然后再进行更新操作。

这个是 $reply->topic->increment('reply_count', 1) 查找方式:

file

这个是 $reply->topic()->increment('reply_count', 1) 查找方式:

file

5年前 评论

@Zark 这方法真好,请问这个是怎么打印出来的?

5年前 评论

@hustnzj

\DB::enableQueryLog();

// 这里写查询

dd(\DB::getQueryLog());
5年前 评论

@Zark

奇怪,为什么我测试出来,两个语句的SQL都只有一句呢?而且二者运行时间都几乎一样。代码如下:

.
.
.
class ReplyObserver
{
.
.
.
    public function created(Reply $reply)
    {
        $topic = $reply->topic;
        DB::enableQueryLog();
        $reply->topic->increment('reply_count', 1);
        $reply->topic()->increment('reply_count', 1);
        dd(DB::getQueryLog());
        // 通知作者话题被回复了
        $topic->user->notify(new TopicReplied($reply));
    }
.
.
.

效果:

file

5年前 评论

@hustnzj

file

红框那里已经是一个查询了。

5年前 评论

@Zark 嗯,那里的确是一个查询,但奇怪的是,下面 $reply->topic->increment('reply_count', 1); 又一次用了 `$reply->topic,为什么这里就不会再次查询了呢?

5年前 评论

@hustnzj 我感觉应该是上面那次查询已经将查询到的 topic 放到 $reply 里面去了,后面再调用的话就直接在 $reply 里面找了。

5年前 评论

@Zark 首先这是对象的概念,其次如果你自己打印分析下会发现topic这种方式返回的是一个模型,而topic()这中返回的是关联关系,其中有一个build对象,可以操作increment,调用的是builder源码里面的increment方法。而topic这种是模型方式,调用的是eloqo/model里面的increment方法

5年前 评论

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