【发布时间】:2020-06-17 09:38:45
【问题描述】:
我正在尝试再次学习 Laravel,我已经看过几年了,现在回来重新审视它。
我遇到的问题是,我一直在关注 Laracasts Twitter 项目,一切都很好,但我尝试在 Twitter 上实现教程中未显示的东西 - 即转发和适当的 Twitter 功能,DM 的工作也是.一切都很好并且工作正常,但我在实际获取一些数据时遇到了障碍。
基本上为了简单起见,我有一个 Tweets 表,它处理原始推文和转推,无论构造正确还是错误,它都可以正常工作。但是,当我尝试获取原始推文的作者时,它倒下了。我可以在转储中看到我要查找的内容,并且作者数据在那里,在这种情况下是用户名,但这不是从模型返回的。顺便说一句,这可以毫无问题地修补。
我还有一个 User(带有 tweets() 函数)和 Tweets 模型(带有 User 函数)
我收到此错误,并且数据似乎在那里,我可以看到它,似乎是字符串“Mikedeveloper”,但是当我尝试返回到该视图时无法得到它: https://flareapp.io/share/xPQxBgm1
所以我有:
我的桌子:
模板:
<!-- This isn't a retweet -->
@if(!$tweet['rt'] && !$tweet['tweet_id'])
<h5 class="font-bold mb-4">
<a href="{{$tweet->user->profile()}}">{{$tweet->user->name}}</a>
</h5>
<!-- This is a retweet -->
@else
<h5 class="font-bold mb-4 bg-green-300 p-2 text-white rounded">
<a href="{{$tweet->user->profile()}}">
{{$tweet->user->username}} retweeted:
</a>
<a href="{{route('profile',$tweet->getUserName($tweet))}}">
{{$tweet->getUserName($tweet)}}
</a>
<i class="fa fa-retweet" style="font-size:24px"></i>
</h5>
@endif
型号:
public function getUserName(Tweet $tweet)
{
// Query table on the tweet_id and get the original tweet id and then query
// that row and get the 'user_id'
$user_id = $this::where('tweet_id',$tweet->tweet_id)->get()
->pluck('user_id')[0];
// Use the 'user_id' and get the username of the original tweet.
$username = User::find($user_id)['username'];
ddd($username);
return $username;
}
更新:
使用关系 - 我现在又一次遇到同样的问题,在模型中很好地转储并在修补程序中工作!如果我在模型中转储,它会将用户名显示为字符串,但是当我尝试渲染它时,错误:
$this->find($this->tweet_id)
->user
->username;
最终工作如下:
【问题讨论】:
标签: laravel collections