PHP code example of elkadrey / eloquent-json-relations
1. Go to this page and download the library: Download elkadrey/eloquent-json-relations library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
elkadrey / eloquent-json-relations example snippets
class User extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
protected $casts = [
'options' => 'json',
];
public function locale()
{
return $this->belongsTo(Locale::class, 'options->locale_id');
}
}
class Locale extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
public function users()
{
return $this->hasMany(User::class, 'options->locale_id');
}
}
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->json('options');
$locale_id = DB::connection()->getQueryGrammar()->wrap('options->locale_id');
$locale_id = 'CAST('.$locale_id.' AS INT)';
$table->computed('locale_id', $locale_id)->persisted();
$table->foreign('locale_id')->references('id')->on('locales');
});
class User extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
protected $casts = [
'options' => 'json',
];
public function roles()
{
return $this->belongsToJson(Role::class, 'options->role_ids');
}
}
class Role extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
public function users()
{
return $this->hasManyJson(User::class, 'options->role_ids');
}
}
class User extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
protected $casts = [
'options' => 'json',
];
public function roles()
{
return $this->belongsToJson(Role::class, 'options->roles[]->role_id');
}
}
class Role extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
public function users()
{
return $this->hasManyJson(User::class, 'options->roles[]->role_id');
}
}