I am building a CMS in Laravel with a model with interchangable table names. All modules in this cms are using their own Mysql table. The website in front has is own models like Page, News, Calendar etc. This can differ per website so I need to be flexible.
The Cms model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Cms extends Model
{
protected static $_table;
/**
* Get all of the page's photos.
*/
public function photos()
{
return $this->morphMany('App\Photo', 'imageable');
}
public function scopePage($query, $id)
{
return $query->find($id);
}
public static function fromTable($table, $parms = Array()){
$ret = null;
if (class_exists($table)){
$ret = new $table($parms);
} else {
$ret = new static($parms);
$ret->setTable($table);
}
return $ret;
}
public function setTable($table)
{
static::$_table = $table;
}
public function getTable()
{
return static::$_table;
}
}
The Photo model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
protected $table = 'photos';
/**
* Get all of the owning imageable models.
*/
public function imageable()
{
return $this->morphTo();
}
}
The Photos table is up and running and working.
The way I call a page:
$page = Cms::fromTable({Page|News|Calender etc})->find($id);
// Get photos
var_dump($page->photos);
My problem is that in this case the reference in imageable_type is allways App\Cms. It should be App{tablename} because the have to be related to different models/tables. I know it is possible to add an extra field for that but in my perspective it seems logical to let the relation create a valid imageable_type value.
Can someone lead me the way?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire