如何使用Laravel联接三个表并保持数据完整性 [英] How to join three tables with Laravel and keep data integrity
问题描述
我正在使用Laravel 5.7,现在我正在尝试在名为以下三个表之间建立关系:
I am using Laravel 5.7 and now I am trying setup a relationship between three tables named:
- 门票(PK-门票ID,FK-校园ID)
- 校园(PK-校园ID,FK-TechID)
- 用户(PK-TechID)
我认为我正在正确显示我的模型,因为我正在显示CampusID
不属于TechID
的票证.我正在寻找设置Eloquent的最佳做法,以保持数据完整性,这样我就可以防止出现任何异常情况.如上所述,Tickets
的外键应引用Campus
主键,而Campus
外键应引用User
主键.
I don't think I set up my models correctly as I am showing a ticket where the CampusID
doesn't belong to the TechID
. I am looking for a best practice on setting up Eloquent to keep the data integrity in place so I can prevent any abnormalities. As mentioned above the foreign key for Tickets
should reference the Campus
primary key, and Campus
foreign key should reference the User
primary key.
这是我的Models
:
门票
protected $table='tickets';
public function user() {
return $this->belongsTo(User::class);
}
校园
protected $table='campus';
public function user() {
return $this->belongsTo(User::class);
}
用户
public function campus()
{
return $this->hasMany(Campus::class, 'TechID');
}
public function ticket()
{
return $this->hasMany(Ticket::class, 'AssignedTo');
}
这是我的控制人:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App\Campus;
use App\Ticket;
class PagesController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
// Dashboard Page
public function index()
{
$user = Auth::user();
$campuses = Campus::where('TechID',$user->id)->pluck('CampusName');
$tickets = Ticket::all()->where('AssignedTo', $user->id);
return view('home')->with(['user' => $user,'campuses'=>$campuses,'tickets'=>$tickets]);
}
// Queue Page
public function Queue() {
return view('Pages.Queue');
}
// Reports Page
public function Reports() {
return view('Pages.Reports');
}
// Search Page
public function Search() {
return view('Pages.Search');
}
}
我认为我的模型很好,但是我的控制器可能是我犯了一些错误的地方.我已经尝试过在这里阅读问题,观看视频和阅读Laravel文档,但是还没有什么真正吸引我的地方.我非常感谢您提供的所有帮助.理想情况下,它应该级联更改.因此,如果我要更改某个技术所属的位置,可以在TechID
列中的Campus
表中进行更改.
I think my models are fine, but my controller is probably where I made some mistakes. I've tried reading questions on here already, watching videos, and reading the Laravel docs, but nothing has really clicked with me yet. I really appreciate any and all help. Ideally it should cascade changes. So if I have a situation where I want to change what location a tech belongs to I could just make the change in the Campus
table probably in the TechID
column.