doubingqi5829 2016-07-18 10: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 10: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部