dousui6488 2016-12-30 02:15 采纳率: 100%
浏览 52

Laravel属于ToMany,无法解决它

I have a jokes, joke_tags, tags table. And I'm trying to get all tags that match the joke ID.

class Joke extends Model
{
    public function tags() {
        return $this->belongsToMany('App\Tag', 'joke_tags', 'tag_id', 'joke_id');
    }
}

My Tag model:

class Tag extends Model
{
    public function jokes() {
        return $this->belongsToMany('App\Joke');
    }
}

Both functions tags() and jokes() don't work... I've been struggling with that for 2 hours now.

My db layout:

Schema::create('jokes', function (Blueprint $table) {
    $table->increments('ID');
    $table->string('author');
    $table->longText('joke');
    $table->timestamps();
});

Schema::create('joke_tags', function (Blueprint $table) {
    $table->increments('ID');
    $table->integer('joke_id')->unsigned();
    $table->foreign('joke_id')->references('ID')->on('jokes');
    $table->integer('tag_id')->unsigned();
    $table->foreign('tag_id')->references('ID')->on('tags');
});

Schema::create('joke_votes', function (Blueprint $table) {
    $table->increments('ID');
    $table->integer('joke_id')->unsigned();
    $table->foreign('joke_id')->references('ID')->on('jokes');
    $table->string('IP');
    $table->boolean('type');
});

Schema::create('tags', function (Blueprint $table) {
    $table->increments('ID');
    $table->string('tag');
});
  • 写回答

1条回答 默认 最新

  • duanhuizhe6767 2016-12-30 02:19
    关注

    Add this to both of your models and you would be good to go.

    protected $primaryKey = 'ID';
    

    EDIT: You should define the relationships as follows besides adding the above property.

    class Joke extends Model
    {
        public function tags() {
            return $this->belongsToMany('App\Tag', 'joke_tags', 'joke_id', 'tag_id');
        }
    }
    
    class Tag extends Model
    {
        public function jokes() {
            return $this->belongsToMany('App\Joke', 'joke_tags', 'tag_id', 'joke_id');
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口