繁体   English   中英

在Laravel 4 Eloquent ORM中创建子关系时出错

[英]Error creating children relationship in Laravel 4 Eloquent ORM

我有一个具有2个这样的模型的结构:

class Contenuti extends Eloquent {
    public function dettaglio()
    {
        return $this->hasOne('ContenutiDettaglio', 'contenuto_id');
    }
}

class ContenutiDettaglio extends Eloquent {
    public function contenuto()
    {
        return $this->belongsTo('Contenuti', 'contenuto_id', 'id');
    }
}    

我正在尝试扩展Contenuti的findOrNew,以便在创建Contenuti时始终添加一个ContenutiDettaglio项目。

我写了这样的扩展名:

public static function findOrNew($id, $coloumns = array())
{
    $obj = parent::findOrNew($id);

    if(!isset($obj->dettaglio()->id))
    {
      $obj->save();

      $dettaglio = ContenutiDettaglio::create(array('titolo' => 'Nuovo contenuto'));
      $dettaglio->contenuto()->associate($obj);

      $obj = Contenuti::findOrFail($obj->id);

      dd($obj->dettaglio());
    }

    return $obj;
}

在数据库中,ContenutiDettaglio中的记录正确包含了父ID,但是当我转储$ obj-> dettaglio()时,其为空。 难道我做错了什么?

编辑:

这是我的迁移:

#Contenuti
public function up()
{
    Schema::create('contenuti', function($t) {
            $t->engine = 'MyISAM';

            // vecchia tabella "contenuti"    
            $t->increments('id');
            $t->bigInteger('userid')->nullable();
            $t->boolean('pubblica');

            // vecchia tabella "contenuti_it"
            $t->timestamp('pubblica_dal')->nullable();
            $t->timestamp('pubblica_al')->nullable();

            $t->timestamps();

            $t->index('pubblica_dal');
            $t->index('pubblica_al');
            $t->index('created_at');
            $t->index('updated_at');
    });
}

#ContenutiDettaglio
public function up()
{
    Schema::create('contenuti_dettaglio', function(Blueprint $table)
    {
        $table->engine = 'MyISAM';

        $table->increments('id');
        $table->integer('contenuto_id');
        $table->string('keywords', 255);
        $table->string('titolo', 255);
        $table->text('sottotitolo');
        $table->text('occhiello');
        $table->text('riassunto');
        $table->text('descrizione');

        $table->index('contenuto_id');
        $table->index('titolo');
    });
}

其中contenuti_dettaglio中的contenuto_id是2个表之间的键。

首先,这是Eloquent中有关关系的文档: http : //laravel.com/docs/4.2/eloquent#relationships

因此,hasOne的基本语法是:

return $this->hasOne('ClassName', 'foreign_key', 'local_key');

默认情况下, foreign_keylocal_key等于“ id”。 foreign_key是关系的主键。

对于belongsTo,它是:

return $this->belongsTo('ClassName', 'local_key', 'foreign_key');

默认情况下, local_keyforeign_key再次等于“ id”。 Contenuti模型中子项的键由hasOne方法的foreign_key定义。 我不知道您的确切数据库架构,但是我想您可以通过更改来解决此问题:

return $this->belongsTo('Contenuti', 'contenuto_id', 'id');

return $this->belongsTo('Contenuti', 'id', 'contenuto_id');

让我知道这是否有效,如果无效,请为这些表附加迁移文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM