du67560 2019-02-28 13:07 采纳率: 0%
浏览 8
已采纳

Laravel,四种模特关系

I have four models: Animal(which can only be "dog" or "cat"), Category, Breed and Post.

Table data:

Animal: - id - name

Category: - id - name - animal_id

Breed: - id - name - category_id

Post: - id - breed_id

What I need is to get all Posts that are about dogs. Have any ideas?

Update: My models:

class Animal extends Model
{

    public function categories()
    {
        return $this->hasMany(Category::class)->orderBy('name', 'ASC');
    }
}

class Category extends Model
{

    public function animal()
    {
        return $this->belongsTo(Animal::class);
    }

    public function breeds()
    {
        $this->hasMany(Breed::class)->orderBy('name', 'ASC');
    }
}

class Breed extends Model
{

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function posts()
    {
        return $this->hasMany(Posts::class);
    }
}

class Posts extends Model
{

    public function breed()
    {
        return $this->belongsTo(Breed::class);
    }

}
  • 写回答

1条回答 默认 最新

  • dow57588 2019-02-28 13:18
    关注

    First of all you need to properly set up the relations in the eloquent models, here is an example of code,

    For Post Eloquent Model And post must have the column animal_id

    public function animal(){
    
        return $this->belongsTo(Animal::class);
    }
    

    Then you have to query like

    $posts = Post::whereHas('animal',function($q){
        return $q->where('name','dog');});
    

    After that you will get the posts which belongs to animal data where animal name is dog. And if you want to query with your current database structure that is not recommended because of complex and long query.

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

报告相同问题?

悬赏问题

  • ¥15 汇编语言没有主程序吗?
  • ¥15 这个函数为什么会爆内存
  • ¥15 无法装系统,grub成了顽固拦路虎
  • ¥15 springboot aop 应用启动异常
  • ¥15 matlab有关债券凸性久期的代码
  • ¥15 lvgl v8.2定时器提前到来
  • ¥15 qtcp 发送数据时偶尔会遇到发送数据失败?用的MSVC编译器(标签-qt|关键词-tcp)
  • ¥15 cam_lidar_calibration报错
  • ¥15 拓扑学,凸集,紧集。。
  • ¥15 如何扩大AIS数据容量