[英]SQLSTATE[23000]: Integrity constraint violation: 1052 using join with laravel
[英]SQLSTATE[23000]: Integrity constraint violation: 1052. Laravel eloquent issue when joining table
我有 News 表,並且刀片表中posted by
的列是空的,但在我的新聞表中,發布者的列users_id
具有users_id
值。 我無法獲取在特定學校發布特定新聞的用戶。 我已經對新聞進行了有效查詢,但問題是我無法加入發布新聞的用戶name
所在的users
表。 有人可以知道我的查詢有什么問題嗎? 幫助將不勝感激。 謝謝
索引 controller
public function index()
{
//testing query that returns an error
$userschool = Newsboard::select('users.name', 'news.school_id')
->join('users', 'users.id', '=', 'news.users_id')
->where('school_id', Auth::user()->school_id)->get();
//the query that i want still returns an error because of the auth
$postedby = DB::select(
"SELECT news.*, users.name as postedby from news
JOIN users on news.users_id = users.id
WHERE news.school_id AND news.active = 1 AND news.school_id = 'Auth::user()->school_id'");
//working queries and i dont know how to convert the $postedby query join to eloquent.
if (Auth::user()->role == 0) {
$news = Newsboard::where('active','=',1)->get();
} elseif (Auth::user()->role == 1 || Auth::user()->role == 5) {
$news = Newsboard::where('school_id', '=', Auth::user()->school_id )
->where('active','=',1)
->get();
} else {
$role = Auth::user()->role;
$news = Newsboard::where('school_id', '=', Auth::user()->school_id )
->where('status', '=', 1)
->where('active','=',1)
->whereRaw("group_id in('$role', '0')")
->get();
}
dd($userschool);
return view('admin.pages.news.index', [
'page_title' => $this->page_title,
'news' => $news,
'mnuname' => 'News',
]);
}
因為users
和news
表都包含school_id
列,所以 where 條件中必須有table
前綴。
請試試:
$userschool = Newsboard::select('users.name', 'news.school_id')
->join('users', 'users.id', '=', 'news.users_id')
->where('news.school_id', Auth::user()->school_id)->get();
//or
//the query that i want still returns an error because of the auth
$postedby = DB::select("SELECT news.*, users.name as postedby from news
JOIN users on news.users_id = users.id
WHERE news.school_id AND news.active = 1 AND news.school_id = '".Auth::user()->school_id."'");
將您的 Auth::user()->school_id 設置為變量
$school_id = Auth::user()->school_id;
//the query that i want still returns an error because of the auth
$postedby = DB::select(
"SELECT news.*, users.name as postedby from news
JOIN users on news.users_id = users.id
WHERE news.school_id AND news.active = 1 AND news.school_id = '$school_id'");
或這個:
Newsboard::select('users.name', 'news.school_id')
->join('users', 'users.id', '=', 'news.users_id')
->where(['news.school_id' => $school_id])->get();
$school_id = Auth::user()->school_id;
$userschool = Newsboard::select('users.name', 'news.school_id')
->join('users', 'users.id', '=', 'news.users_id')
->where('school_id', $school_id)->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.