【发布时间】:2021-12-31 13:01:42
【问题描述】:
这件事以前发生在我身上,但我不知道为什么以及如何避免它。所以我在模型中有一个静态函数,它获取所有数据库行并使用 foreach 循环读取另一个表,但我无法正确读取行数据:
public static function test()
{
$accounts = self::where( 'is_enabled', 1 )->get();
foreach ( $accounts as $account ) {
$map = AccountMap::where( 'account_id', $account->id )->first();
$location = Location::getLocation( $map->location_id );
$data = $location->getData();
}
}
所以上面的函数收集了一个项目数组($accounts),然后将其传递到一个 foreach 循环中,到目前为止一切都很好,但是如果我现在使用 $account->id 它是空的。 id 显示在其属性文件夹中的 Account 对象中。
在此模型的其他地方使用了一个非常相似的函数,但它使用传递的 id 并且这个函数有效(但是 $account->id 为空)。问题不在于数据库或列名:
public static function getThisLocation( $id )
{
$account = self::find( $id );
$map = AccountMap::where( 'account_id', $id )->first();
location = Location::getLocation( $map->location_id );
$data = $location->getData();
return $data;
}
*** 编辑 *** Account、AccountMap 和 Location 都是 Eloquent 模型
namespace App\Models;
use Eloquent;
use App\Notifications\AccountMessages;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Notifications\Notifiable;
/**
* @method static find(int $id)
*/
class Account extends Eloquent
{
use Sortable;
use Notifiable;
public $sortable = [
'id',
'name',
'lastupdate',
'url'
];
public static function test()
{
$accounts = self::where( 'is_enabled', 1 )->get();
foreach ( $accounts as $account ) {
$map = AccountMap::where( 'account_id', $account->id )->first();
$location = Location::getLocation( $map->location_id );
$data = $location->getData();
}
}
public static function getThisLocation( $id )
{
$account = self::find( $id );
$map = AccountMap::where( 'account_id', $id )->first();
location = Location::getLocation( $map->location_id );
$data = $location->getData();
return $data;
}
}
namespace App\Models;
use Eloquent;
use Kyslik\ColumnSortable\Sortable;
/**
* @method static where(string $string, int $id)
*/
class AccountMap extends Eloquent
{
use Sortable;
public $sortable = [
'id',
'account_id',
'location'
];
}
*** 更多编辑 *** 我已经确认使用 $account->attributes['id'] 有效,但我不知道为什么我期望的工作没有($account->id)
【问题讨论】:
-
所以
$map不是一个对象。因此$map = AccountMap::where( 'account_id', $account->id )->first();要么不返回一个对象,要么它没有返回任何东西 -
问题是 $account->id 返回 null,所以 $map 找不到数据
-
我们在这里讨论的是哪个版本?因为我认为应该是
extends Model,它最终甚至可能会回答最近更新的问题...