I am using make() and I don't want to persist anything to that particular database. The problem is that I'm just getting an empty model back. It's the correct model (based on the defined connection, table, and primaryKey properties, but it has no attributes.
Do the properties have to exist in the model class? Since it's only for retrieving data, I basically have an empty model class and the ORM populates it nicely. I do have PhpUnit set to use sqlite all db connections whether I actually need them or not.
The model:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
use HasFactory;
protected $connection;
protected $table = 'view_Employee';
protected $primaryKey = 'EmployeeNumber';
protected $keyType = 'string';
public $incrementing = FALSE;
public $timestamps = FALSE;
public function __construct()
{
$this->connection = config('aep.db_connection.gpdb');;
}
}
and the factory:
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Employee>
*/
class EmployeeFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
$lname = fake()->lastName;
$fname = fake()->firstName;
$mname = fake()->firstName;
$title = fake()->title;
return [
'EmployeeNumber' => fake()->numberBetween(1001, 1999),
'LastName' => $lname,
'FirstName' => $fname,
'MiddleName' => $mname,
'Nickname' => '',
'AltName' => '',
'Suffix' => '',
'Prefix' => $title,
'DisplayName' => join(' ', array_filter([$title, $fname, $mname, $lname])),
'SSN' => fake()->randomNumber(9),
'Gender' => fake()->randomElement(['M', 'F']),
'Email' => fake()->email,
'PersonalPhone' => fake()->phoneNumber,
'OtherPhone' => fake()->phoneNumber,
'OfficePhone' => fake()->phoneNumber,
'OfficeExt' => fake()->randomNumber(4),
'DOB' => fake()->date,
'Address1' => fake()->streetAddress,
'Address2' => '',
'Address3' => '',
'City' => fake()->city,
'State' => '',
'Zip' => fake()->postcode,
'Country' => '',
'JobDescription' => fake()->jobTitle,
'Department' => '',
'OfficeLocation' => Str::random(2) . fake()->randomNumber(3),
'DirPhone' => fake()->boolean ? 1 : 0,
'DirAddress' => fake()->boolean ? 1 : 0,
];
}
}
and the test (fails):
namespace Tests\Models;
use App\Models\Employee;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class EmployeeTest extends TestCase
{
use RefreshDatabase;
public function testHasAnEmployeeNumber()
{
$e = Employee::factory()->make();
$this->assertObjectHasProperty('EmployeeNumber', $e);
}
}