我现在创建用于从消息表中获取所有当前用户消息的函数。通常我可以使用另一个函数更改当前数组值。例如,我必须以所需格式获取发送日期。还可以使用发件人ID从用户表中获取电子邮件。
public function user_messages()
{
$user_id = Auth::user()->id;
$messages = Message::where('to', $user_id)->get();
foreach ($messages as $message)
{
echo $message->subject; // Example Subject
echo $message->message; // Long message text
echo $message->from; // Sender id. For example: 2
echo $message->created_at; // Sended date
}
//return $messages;
}
我可以在另一个返回所需视图的Controller上调用此函数吗?
现在我写另一个函数来获取电子邮件。这个方法好还是不好?
public function getEmail($id)
{
return User::where('id', $id)->first()->email;
}
foreach ($messages as $message)
{
echo $this->getEmail($message->from)."<br>";
}
答案 0 :(得分:2)
您可以在消息中使用雄辩的关系模型添加发送者和接收者功能
public function sender() {
return $this->belongsTo(User::class, 'from');
}
public function receiver() {
return $this->belongsTo(User::class, 'to');
}
并根据需要格式化日期:
public function getCreatedAT($value) {
return $this->attributes['created_at']->toIso8601String();
}
然后您可以访问$ message-&gt;发件人和$ message-&gt;接收者以获取电子邮件;
答案 1 :(得分:0)
如果我理解你的问题而不是我认为最适合你的问题,那就是使用范围和关系:
消息模型:
/**
* Sender relation
*
* @return User
*/
public function sender() {
return $this->belongsTo(User::class, 'from');
}
/**
* Receiver relation
*
* @return User
*/
public function receiver() {
return $this->belongsTo(User::class, 'to');
}
/**
* scope that return only messages which send specific user
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeSentToUser($query, $user_id == null)
{
if (!$user_id && !\Auth::check()) {
throw new \InvalidArgumentException('User ID is undefined');
} else {
$user_id = \Auth::id();
}
return $query->whereHas('receiver', function($sql) use ($user_id) {
$sql->where('id', $user_id);
});
}
任何控制器:
/** @var \Illuminate\Database\Eloquent\Collection $messages Messages which were sent to auth user **/
$messages = Message::sentToUser()->get();
/** @var \Illuminate\Database\Eloquent\Collection $messages Messages which were sent to user 2 **/
$anotherUserMessages = Message::sentToUser(2)->get();
foreach ($messages as $message)
{
echo $message->subject; // Example Subject
echo $message->message; // Long message text
echo $message->from; // Sender id. For example: 2
echo $message->created_at; // Sent date
var_dump($message->sender); // Sender user model
var_dump($message->receiver); // Receiver user model
}