我得到了错误;
模型App\UserProfile 0没有查询结果
当我使用findOrFail时,使用一个与AJAX一起在foreach循环中传递的数组。如果我在PHP中手动创建数组,则可以使用数组值找到该实体。当我在PHP中对数组执行print_r()时,这个数组同时存在于AJAX数组和手动创建的数组中。
AJAX代码
function checkChatOnlineStatus()
{
var chatUserProfileIds = {"key-60":60,"key-52":52,"key-2":2,"key-3":3}
$.ajax({
url: '/check-chat-online-status',
method: 'get',
data: {chatUserProfileIds: chatUserProfileIds},
dataType: 'json',
success: function(response) {
}
});
}PHP代码
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\UserProfile;
class CheckRunningParametersController extends Controller
{
public function checkChatOnlineStatus()
{
$chatUserProfileIds = $_GET['chatUserProfileIds'] ? $_GET['chatUserProfileIds'] : NULL;
//$chatUserProfileIds = array('key-60' => 60, 'key-52' => 52, 'key-2' => 2, 'key-3' => 3);
/* Check Status For Chat Contacts */
if ($chatUserProfileIds != NULL)
{
foreach ($chatUserProfileIds as $key => $value)
{
$userProfile = UserProfile::findOrFail((int)$value);
$chatOnlineStatus['contacts'][$key] = $userProfile->isOnline();
}
}
return $chatOnlineStatus;
}
}发布于 2017-12-15 11:47:21
我发现了问题。真是愚蠢的错误。我将数据分配到数组中使用的JavaScript对象到全局范围,这似乎是可行的。
// Moved this to global scope in the Javascript
var chatUserProfileIds = {"key-60":60,"key-52":52,"key-2":2,"key-3":3}发布于 2017-12-11 04:10:11
如果id中没有findOrFail(),则使用findOrFail()将引发异常。您可能正在将id号推回不存在的Laravel DB。如果您不希望出现异常,并希望进行自检查,请使用first()或find(),然后对isset进行If检查,以查看模型是否返回,如果ID与UserProfile不匹配,则为空值。IE:
$userProfile = UserProfile::find((int)$value);
if(isset($userProfile)
$chatOnlineStatus['contacts'][$key] = $userProfile->isOnline();如果您确信UserProfile存在您要传递的If,则可能是字符串以错误的方式转换为int的问题。检查通过dd()传递什么(int)。您还可能希望使用本机Laravel \get::get(‘chatUserProfileIds’)而不是$_GET。
发布于 2017-12-11 05:05:14
这里,您的PHP代码将如下所示
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\UserProfile;
class CheckRunningParametersController extends Controller
{
public function checkChatOnlineStatus()
{
$chatUserProfileIds = $_GET['chatUserProfileIds'];
/* Check Status For Chat Contacts */
if ($chatUserProfileIds != NULL)
{
foreach ($chatUserProfileIds as $key => $value)
{
$userProfile = UserProfile::where("id",(int)$value)->first();
$chatOnlineStatus['contacts'][$key] = $userProfile->isOnline();
}
}
return $chatOnlineStatus;
}
}https://stackoverflow.com/questions/47746249
复制相似问题