doubingqi5829 2016-07-18 18:50
浏览 48
已采纳

Laravel Relation belongsTo id无法识别

I have those schemas:

Schema::create('tickets', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('ticket_reason_id')->unsigned();
    $table->integer('user_id')->unsigned();
    $table->timestamps();
    $table->foreign('ticket_reason_id')->references('id')->on('ticket_reasons')->onDelete('cascade');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

Schema::create('ticket_reasons', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamps();
});

And those defined relationships

class Ticket extends Model
{

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function reason()
    {
        return $this->belongsTo(TicketReason::class, 'ticket_reason_id');
    }

}

The "reason" method works but I had to manually add the ID. Why do I have to add the id if I'm following the convention? (or at least I think so). It follows the same convention than the user_id column and it doesnt need the id setter.

  • 写回答

1条回答 默认 最新

  • donglie9067 2016-07-19 18:17
    关注

    So, I'm going to fault Laravel's Eloquent documentation on this one...since, it's really not too clear on how the foreign key is auto-generated. I did find this, from the Eloquent Relationships page, though (emphasis mine):

    Eloquent will try to match the user_id from the Phone model to an id on the User model. Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id.

    Contrary to what one (you, myself, etc.) may assume, the foreign key is not generated by the foreign class's name. Instead, it uses the name of the method that your ::belongsTo() (or hasOne(), etc.) call is in.


    This means that public function reason() {} needs to be changed to public function ticket_reason() {}. Or, of course, you could change your column name to reason_id.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解