2017-10-14 54 views
0

我不得不说我的代码工作正常,但我不明白为什么......我想为不同的“模块”添加一些自定义字段。我的多态关系的解释

例如,我有3个表格:相机,服务器和custom_fields。

相机&服务器型号:

Schema::create('description_fields', function (Blueprint $table) { 
    $table->increments('id'); 
    $table->integer('item_id')->unsigned(); 
    $table->string('item_type'); 
    $table->string('name'); 
    $table->string('value'); 
    $table->timestamps(); 
}); 

我可以在控制器通过这条线添加一些元素:

$camera->custom_fields()->attach($request->custom_field); 

我的问题

public function custom_fields() 
{ 
    return $this->morphToMany('App\Models\Camera', 'item', 'description_fields', '', 'name') 
     ->withPivot('name', 'value') 
     ->withTimestamps(); 
} 

此关系表是关于模型,为什么我写:

morphToMany( '应用程序\型号\相机', '项', 'description_fields', '', '名')

我不明白为什么我必须指定最后2个参数:' ','name'(用'value'改变'name'并且它正在工作,但是如果我删除'','name'它不起作用)。

我已经阅读了params的文档,但我仍然不明白(我不是专业开发人员,但我自己学习)。如果任何人可以花5分钟解释我,它将不胜感激。

在此先感谢。

回答

0

看看Laravel的源代码,morphToMany方法:

/** 
* Define a polymorphic many-to-many relationship. 
* 
* @param string $related 
* @param string $name 
* @param string $table 
* @param string $foreignKey 
* @param string $relatedKey 
* @param bool $inverse 
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany 
*/ 
public function morphToMany($related, $name, $table = null, $foreignKey = null, $relatedKey = null, $inverse = false) 
{ 
    $caller = $this->guessBelongsToManyRelation(); 

    // First, we will need to determine the foreign key and "other key" for the 
    // relationship. Once we have determined the keys we will make the query 
    // instances, as well as the relationship instances we need for these. 
    $instance = $this->newRelatedInstance($related); 

    $foreignKey = $foreignKey ?: $name.'_id'; 

    $relatedKey = $relatedKey ?: $instance->getForeignKey(); 

    // Now we're ready to create a new query builder for this related model and 
    // the relationship instances for this relation. This relations will set 
    // appropriate query constraints then entirely manages the hydrations. 
    $table = $table ?: Str::plural($name); 

    return new MorphToMany(
     $instance->newQuery(), $this, $name, $table, 
     $foreignKey, $relatedKey, $caller, $inverse 
    ); 
} 

要设置$foreignKey为“”和$relatedKey为“名”。在这部分具体看:

$relatedKey = $relatedKey ?: $instance->getForeignKey(); 

这基本上说,如果你给我一个$relatedKey使用它从其他模型实例得到它。

如果您访问Model.php以查看getForeignKey方法的源代码,您将看到类名+'_'+默认主键('id')的串联结果。所以这导致'camera_id'。

/** 
* Get the default foreign key name for the model. 
* 
* @return string 
*/ 
public function getForeignKey() 
{ 
    return Str::snake(class_basename($this)).'_'.$this->primaryKey; 
} 
+0

感谢您的快速回复。它只在添加一些数据时才起作用,但当我想从摄像机获取自定义字段时,它不起作用。我想我的关系是不正确的,但是,谢谢,我会尽力得到它! – alexcool68

+0

我改写了这个关系: 'return $ this-> morphToMany('App \ Models \ Server','item','description_fields','','item_id') - > withPivot('name' ,'value') - > withTimestamps();' 现在工作正常,但我必须在刀片中使用'{{$ custom_field-> pivot-> name}}''。没关系,我明白了! – alexcool68