【问题标题】:Laravel 5.3 relationship issue, Column not foundLaravel 5.3 关系问题,找不到列
【发布时间】:2016-11-06 20:13:03
【问题描述】:
class Company extends Model
{
 public function employees() {
    return $this->hasMany('Employee');   
}
}
class User extends Model
{
public function employee()
{
    return $this->hasMany('Employee');
}
}
class Employee extends Model
{
protected $table = "user_role_company";

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

我在运行时得到“Column not found: 1054 Unknown column 'user_id' in 'where clause' (SQL: select * from companies where user_id = 55)”:

Company::with('employees')->where('user_id',$user->id)->get();

我做错了什么?

谢谢

【问题讨论】:

  • 您的架构在哪里?您是否试图为特定用户获取属于公司的员工?

标签: php mysql laravel


【解决方案1】:

你可以试试:

Company::whereHas('employees', function($query) use($user) {
           $query->where('user_id', $user->id);
        })
        ->with('employees')
        ->get();

【讨论】:

    【解决方案2】:

    使用闭包在with 上使用filter

    Company::with(['employees' => function($q) use($user) {
        return $q->where('user_id', $user->id);
    }]);
    

    【讨论】:

    • 返回所有公司
    猜你喜欢
    • 2017-04-28
    • 2017-12-13
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 2017-05-13
    • 2017-06-21
    相关资源
    最近更新 更多