【问题标题】:Polymorphic Relations in Laravel naming convenstionLaravel 命名约定中的多态关系
【发布时间】:2016-06-07 05:15:57
【问题描述】:

我将在 Laravel 中创建多态关系,但我的表太旧了,而且它的命名约定不符合 laravel。我可以这样做吗?如何做?

【问题讨论】:

  • 最好添加有关您当前数据库架构的更多信息。
  • 你能添加你的代码吗?

标签: laravel polymorphism polymorphic-associations


【解决方案1】:

当然你可以直接设置你的表名和FK列名。
查看 Realtion docs,如有必要,请查看 Laravel APIsource code

如果你有

posts
    id - integer
    title - string
    body - text

comments
    id - integer
    post_id - integer
    body - text

likes
    id - integer
    likeable_id - integer
    likeable_type - string

那么你的代码将是

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Like extends Model
{
    /**
     * Get all of the owning likeable models.
     */
    public function likeable()
    {
        return $this->morphTo('likeable', 'likeable_type', 'likeable_id');
    }
}

class Post extends Model
{
    /**
     * Get all of the post's likes.
     */
    public function likes()
    {
        return $this->morphMany('App\Like', 'likeable', 'likeable_type', 'likeable_id');
    }
}

class Comment extends Model
{
    /**
     * Get all of the comment's likes.
     */
    public function likes()
    {
        return $this->morphMany('App\Like', 'likeable', 'likeable_type', 'likeable_id');
    }
}

【讨论】:

    猜你喜欢
    • 2016-09-21
    • 2014-03-12
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 2017-02-01
    相关资源
    最近更新 更多