I've been using this package frequently to create Models based on a remote API using the custom getRows method provided in the package.
The problem I'm trying to figure out is in the Model you have getRows(), which queries and API and returns the results. You can then use standard eloquent queries like 'first'. I need to pass a variable into this method so that the API can pull back different results based on its own parameters.
How can I set a variable in the Model to use in getRows() from an Eloquent query. Something like:
MyModel::setVariable($var)->first();
Or something similar.. The issue is I need to set this variable before the model returns any results.
class MyModel extends Model
{
use Sushi;
public function getRows($var) // how can I set this?
{
$data = $api->query()->where(function ($query) use ($var) {
return $query->where('id', 'eq', $var); // dynamic lookup based on variable
})->get();
return $data;
}
I am also experiencing the same issue. The second call on the sushi class isn't functioning as expected. Using the cache method doesn't resolve the problem. Have you found a solution?
@v-tev I just stumbled into this same problem. So I will put here my solution, I do not think is the best one available, but it solved for my necessity.
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
class Foo extends Model
{
use \Sushi\Sushi;
/** @var string */
protected static $bar;
/** Cache result for specific $bar */
protected function cacheKey(): Attribute
{
return Attribute::make(
get: fn () => sprintf('foo_api_result_%s', self::$bar),
);
}
/** This will create a table for each bar */
public function getTable()
{
return 'foo_'.self::$bar;
}
/** This will set up the $bar value before querying the results */
public function bar(string $bar)
{
self::$bar = $bar;
$cacheKey = (new static)->cacheKey;
/**
* Not only it will avoid recreating the same table, but also
* will create a new table for any $bar value.
*/
if (Cache::get($cacheKey) == null) {
(new static)->migrate();
}
return self::query();
}
public function getRows()
{
/** This will launch an exception if not queried using bar() */
if (self::$bar == null) {
throw new InvalidArgumentException('Model is missing the $bar property');
}
return Cache::remember(
$this->cacheKey,
now()->addHour(),
function () {
sleep(3); // This sleep is just to test the Cache for every set of results
return [
[
'id' => random_int(0, PHP_INT_MAX),
'filter' => self::$bar,
],
];
}
);
}
}
What it will do is to create a table for every $bar passed as argument when calling bar(). Something like bar('baz') will result into a table called foo_baz