douzhaxian1267 2017-01-26 12:58
浏览 81
已采纳

在laravel模型中处理关系

I am learning relationships in Laravel php framework and I am trying to build this query

SELECT * FROM users u INNER JOIN link_to_stores lts ON u.id=lts.user_id INNER JOIN stores s ON lts.store_id=s.store_id WHERE lts.privilege = 'Owner'

I built this in Model

Link_to_store.php

public function store()
{
    return $this->belongsTo('App\Store');
}

public function user()
{
    return $this->belongsTo('App\User');
}

User.php

public function store_links()
{
    return $this->hasMany('App\Link_to_store');
}

Store.php

public function user_links()
{
    return $this->hasMany('App\Link_to_store');
}

I tried this query but this only joins user and link_to_store table

$personal_stores = Auth::user()->store_links->where('privilege','=','Owner');

Now I am confused how to join store table too. Can anyone help with this?

Schema is like this

Stores Table

store_id store_name

Users Table

id name

Link_to_stores Table

id store_id user_id privilege

  • 写回答

2条回答 默认 最新

  • dongyan8896 2017-01-26 13:03
    关注

    I suppose store_links is actually a pivot table. In this case, you can use belongsToMany(), this will automatically take care of the pivot table.

    To do this, in your User model you change the store function to this:

    function stores() {
        return $this->belongsToMany('App\Store', 'store_links', 'user_id', 'store_id')->withPivot('privilege');
    }
    

    Because the primary key of stores is not id, you will have to define this in you Store model with the following line:

    protected $primaryKey = 'store_id';
    

    Now to get the stores for a user, you simply call

    $stores = Auth::user->stores()->wherePivot('privilege', 'Owner')->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析