【问题标题】:Laravel not return BelongsToLaravel 不返回 BelongsTo
【发布时间】:2016-07-13 14:27:38
【问题描述】:

谢谢大家,我有两张表,一张名为 Produto,另一张名为 ProdutoCategoria。当我建立模型的关系时,只有 ProdutoCategoria 对象返回了 Produdo,而 Produto 没有返回对象 ProdutoCategoria,为什么?

    class ProdutoCateg extends Model
{
    public function produtos(){
        return $this->hasMany('app\Produto');
    }
}



class Produto extends Model
{
    public function categoria(){
        return $this->belongsTo('app\ProdutoCateg');
    }
}


class Fktables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('produtos', function ($table){
            $table->foreign('id_produto_categs')->references('id')->on('produto_categs');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

【问题讨论】:

  • Produto 返回什么?
  • 你能告诉我们你的迁移吗?不仅是外键创建

标签: laravel laravel-5 eloquent


【解决方案1】:

尝试在关系中添加foreign key 字段,Laravel 无法猜测,因为您没有遵循命名约定 DB 架构。

class Produto extends Model
{
    public function categoria(){
        return $this->belongsTo('App\ProdutoCateg', 'id_produto_categs');
    }
}

示例

Product 模型应该有一个名为 products 的表 ProductCategory 模型应该有一个名为 product_categories 的表, 现在创建与类别的关系使用table_name (singular) + _id,在这种情况下将是product_category_id。我希望这是有道理的。

为了使这项工作自动进行,您需要在 produtos 表上将 FK 更改为 produto_categ_id

【讨论】:

    【解决方案2】:

    您应该尝试将app 更改为App 示例:

    public function produtos {
       return $this->hasMany('App\Produto');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 2016-03-31
      • 1970-01-01
      • 2014-12-11
      • 2020-09-08
      • 2013-05-20
      • 2016-02-29
      相关资源
      最近更新 更多