Php Laravel从数据库中查找数据,直到该值为null或重试完成

Php Laravel从数据库中查找数据,直到该值为null或重试完成,php,laravel,Php,Laravel,在我的web应用程序中,我想在数据库中搜索,当该值为空时,我应该存储新数据,为了检查此操作,我使用do while语句,并使用另一个选项从数据库中检查和搜索,限制期为retry,如下代码: $retry = 0; do { $feed = $feeds[array_rand($feeds)]; $history = InstagramActionsHistory::wherePk($feed->pk)->whereActionName('comment')->f

在我的web应用程序中,我想在数据库中搜索,当该值为空时,我应该存储新数据,为了检查此操作,我使用
do while
语句,并使用另一个选项从数据库中检查和搜索,限制期为
retry
,如下代码:

$retry = 0;
do {
    $feed = $feeds[array_rand($feeds)];
    $history = InstagramActionsHistory::wherePk($feed->pk)->whereActionName('comment')->first();
    $retry++;
} while ($history == null || $retry >= 3);
在此代码中,
while
$history
为空或
$retry
大于或等于
3
时,应该中断语句,但它不能正常工作

而不是此代码正常工作:

$retry = 0;
do {
    $feed = $feeds[array_rand($feeds)];
    $history = InstagramActionsHistory::wherePk($feed->pk)->whereActionName('comment')->first();
    $retry++;
    if ($history == null || $retry >= 3) {
        break;
    }
} while (true);

似乎在while语句中多条件不起作用

您应该使用逻辑运算符

修改代码

<?php 
$retry = 0;
do {
        $feed = $feeds[array_rand($feeds)];
        $history = InstagramActionsHistory::wherePk($feed->pk)->whereActionName('comment')->first();
        $retry++;
} while ($history && $retry >= 3);
?>

在第一种情况下,如果循环3次或更多次,您将得到无限循环

因此,如果您想尝试不超过3次地填充
$history
,则需要将条件指定为:while
$history
NULL
且$retry不超过3次

$retry = 0;
do {
    $feed = $feeds[array_rand($feeds)];
    $history = InstagramActionsHistory::wherePk($feed->pk)->whereActionName('comment')->first();
    $retry++;
} while ($history == null && $retry < 3);
$retry=0;
做{
$feed=$feeds[array_rand($feeds)];
$history=InstagramActionsHistory::wherePk($feed->pk)->wherectionname('comment')->first();
$retry++;
}而($history==null&&$retry<3);

这里是修正,而($history==null | |$retry>=3);请再次尝试第一个代码。@VasimVanzara当
$history
为null
语句不中断时,您应该使用短路运算符并使用条件因为
first()
将返回一个项或null,您应该在($history | |$retry>=3)时执行