gpt4 book ai didi

laravel-4 - 如何在 laravel 4 中同时使用 Eager Loading 和 Join in Eloquent

转载 作者:行者123 更新时间:2023-12-02 04:41:21 26 4
gpt4 key购买 nike

模型

class WPModel extends Eloquent
{

protected $table = 'work_processes';
protected $guarded = array('id');
protected $softDelete = true;

// declaring one-to-many relationship
public function relatedWPAQs()
{
return $this->hasMany('WPAQModel', 'wp_id');
}

public function relatedUsers()
{
return $this->belongsTo('UserModel', 'wp_owner_id');
}

}

class UserModel extends Eloquent
{
protected $table = 'users';
protected $softDelete = true;

public function relatedWPs()
{
return $this->hasMany('WPModel', 'wp_owner_id');
}
}

class WPAQModel extends Eloquent
{
protected $table = 'wp_audit_questions';
protected $fillable = array('wp_id', 'wp_audit_question');

// declaring one-to-many relationship - the inverse way
public function relatedWP()
{
return $this->belongsTo('WPModel', 'wp_id');
}

public function scopeWpParent($query, $id)
{
return $query->where('wp_id', '=' ,$id);
}
}

Controller

class WPAQController extends BaseController
{
public function showWPAQ($wpid)
{
$workprocess = WPModel::where('id', $wpid)
->join('users', 'users.id', '=', 'work_processes.wp_owner_id')
->select('users.user_name', 'work_processes.*')
->with(array(
'relatedWPAQs' => function($query) use ($wpid)
{
$query->where('wp_id', '=',$wpid);
}
))
->get();
return View::make('wpaqshow')->with(compact('workprocess'));
}
}

当我运行这段代码时,出现以下错误

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select users.user_name, work_processes.* from work_processes inner join users on users.id = work_processes.wp_owner_id where work_processes.deleted_at is null and id = ?) (Bindings: array ( 0 => '1', ))

最佳答案

尝试以下操作:

$workprocess = WPModel::where('work_processes.id', $wpid)
->join('users', 'users.id', '=', 'work_processes.wp_owner_id')
->select('users.user_name', 'work_processes.*')
->with(array(
'relatedWPAQs' => function($query) use ($wpid)
{
$query->where('wp_id', '=',$wpid);
}
))
->get();

您加入了几张 table 。现在 laravel 有很多 Ids。你必须告诉 Laravel 在 where 子句中 Laravel 应该使用哪个 id..

WPModel::where('id', $wpid)

关于laravel-4 - 如何在 laravel 4 中同时使用 Eager Loading 和 Join in Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20780715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com