Есть ли более простой способ кодирования красноречивых моделей, чем у меня здесь? - PullRequest
0 голосов
/ 11 октября 2019

Я создал этот код для работы с laravel 5.8 для доступа к базе данных со многими внешними ключами, похоже, что я подрываю внешние ключи, я что-то упустил, надеялся, что кто-то может указать мне правильное направление. Это работает, но я думаю, что я переусердствовал и упустил некоторые красноречивые ярлыки.

namespace App\Models\Entities;
use Illuminate\Database\Eloquent\Model;
class AbstractModel extends Model
{
    public function isDuplicate(Model $model) {
        return  $model::where($model->getAttributes())->first();
    }
}
///
namespace App\Models\Entities;
abstract class AbstractForeignModel extends AbstractModel {

    public $timestamps = false;
    public $fillable = ['value'];

    public function store($value){
        $foreign = $this->newInstance();
        $foreign->value = $value;
        if(!$this->isDuplicate($foreign)){
            $foreign->save();
        }
        return $foreign->getId($value);
    }

    public function setValueAttribute($value){
        $this->attributes['value'] = $value;
    }

    public function getId($value){
        $result =  self::where('value', $value)->first();
        if($result){
            return $result->id;
        }
    }
    public function getValue($id){
        $result = self::where('id', $id)->first();
        if($result){
           return $result->value; 
        }
    }
}
///
namespace App\Models\Entities\Video;
use App\Models\Entities\AbstractForeignModel;
class ForeignModel extends AbstractForeignModel {
    public function video() {
        return $this->belongsTo('App\Models\Entities\Video');
    }
}

Автор, описание, источник, название расширяют вышесказанное как пустые классы


use App\Models\Entities\Video\Author;
use App\Models\Entities\Video\Description;
use App\Models\Entities\Video\Source;
use App\Models\Entities\Video\Title;
use Carbon\Carbon;
class Video extends AbstractModel {

    protected $fillable = ['author_id', 'title_id', 'description_id',
        'source_id', 'published_at'];

    public function store($data) {
        $video = new Video;
        $video->author_id = $data->author;
        $video->title_id = $data->title;
        $video->description_id = $data->description;
        $video->source_id = $data->source;
        $video->published_at = $data->published_at;
        if (!$this->isDuplicate($video)) {
            $video->save();
        }
    }

    public function setPublishedAtAttribute($value){
        $this->attributes['published_at'] = Carbon::parse($value)->toDateTimeString();
    }

    public function setTitleIdAttribute($value) {
        $this->attributes['title_id'] = (new Title)->store($value); 
    }

    public function setDescriptionIdAttribute($value) {
        $description = (new Description)->store($value);
        $this->attributes['description_id'] = $description;
    }

    public function setSourceIdAttribute($value) {
        $this->attributes['source_id'] =(new Source)->store($value);
    }

    public function setAuthorIdAttribute($value) {
        $this->attributes['author_id'] = (new Author)->store($value);
    }

    public function getAuthorIdAttribute($value) {
        $this->attributes['author_id'] = (new Author)->getValue($value);
    }

    public function getTitleIdAttribute($value) {
        $this->attributes['title_id'] = (new Title)->getValue($value);
    }

    public function getDescriptionAttribute($value) {
        $this->attributes['description_id'] = (new Description)->getValue($value);
    }

    public function getSourceIdAttribute($value) {
        $this->attributes['source_id'] = (new Source)->getValue($value);
    }

    public function author() {
        return $this->belongsTo('App\Models\Entities\Video\Author', 'author_id');
    }

    public function description() {
        return $this->belongsTo('App\Models\Entities\Video\Description', 'description_id');
    }

    public function title() {
        return $this->belongsTo('App\Models\Entities\Video\Title', 'title_id');
    }

    public function source() {
        return $this->belongsTo('App\Models\Entities\Video\Source', 'source_id');
    }
}

файл миграции видео

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateVideosTable extends Migration {
   public function up() {
        Schema::create('videos', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('source_id');
            $table->unsignedBigInteger('title_id');
            $table->unsignedBigInteger('description_id');
            $table->unsignedBigInteger('author_id');
            $table->dateTimeTz('published_at');
            $table->timestamps();
            $table->foreign('source_id')->references('id')->on('sources');
            $table->foreign('title_id')->references('id')->on('titles');
            $table->foreign('description_id')->references('id')->on('descriptions');
            $table->foreign('author_id')->references('id')->on('authors');
        });
    }

    public function down() {
        Schema::dropIfExists('videos');
    }
}

Файлы переноса внешнего ключа следуют этому макету, так как Автор, Описание, Источник, Заголовок

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTitlesTable extends Migration
{
    public $timestamps = false;
    public function up()
    {
        Schema::create('titles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('value');
        });
    }
    public function down()
    {
        Schema::dropIfExists('titles');
    }
}

могут, вероятно, создать класс переноса внешнего ключа и просто установить нужные мне переменные

1 Ответ

0 голосов
/ 11 октября 2019

Вероятно, вам понадобится firstOrCreate

Существует два других метода, которые вы можете использовать для создания моделей путем массового присвоения атрибутов: firstOrCreate и firstOrNew. Метод firstOrCreate попытается найти запись в базе данных, используя заданные пары столбец / значение. Если модель не может быть найдена в базе данных, будет вставлена ​​запись с атрибутами из первого параметра, а также с атрибутами в необязательном втором параметре.

Метод firstOrNew, например firstOrCreate, попытается найтизапись в базу данных, соответствующую заданным атрибутам. Однако, если модель не найдена, будет возвращен новый экземпляр модели. Обратите внимание, что модель, возвращенная firstOrNew, еще не сохранена в базе данных. Вам нужно будет вызвать сохранение вручную, чтобы сохранить его.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...