我在数据库中有两个表,一个叫做票证,一个叫状态(某个票证的状态,如新的或已完成)...每次用户添加票证时,我希望使用票证更新状态表id和状态消息。
使用MYSQL表连接是唯一的方法吗?
public function userSubmitTicket() {
$validator = Validator::make(Input::all(), ['subject' => 'required', 'message' => 'required']);
//if one or more of the text boxes dont contain data, the validator fails and user is returned backa to redo the form
if ($validator->fails()) {
return Redirect::back()->withInput()->withErrors($validator->messages());
}
$user = Auth::user();
$userId = $user->id;
$subject = Input::get('subject');
$message = Input::get('message');
$date = new DateTime();
$ticket = Ticket::insert(array('id' => null, 'date_in' => $date,
'originator_id' => $userId, 'assigned_to_id' => 0, 'date_out' => null,
'priority' => 3, 'subject' => $subject));
$ticketID = Ticket::select('id')->limit(1)->get();
foreach($ticketID as $id){
$status = Status::insert(array('id' => $id, 'description' => 'New'));
}
这是我试过的一种方式,但我知道它现在不起作用。
答案 0 :(得分:1)
您可以尝试这样的事情:
class Ticket extends Eloquent {
//...
protected $guarded = array(); // Check mass-assignment
public function status()
{
return $this->hasOne('Status', 'ticket_id');
}
}
class Status extends Eloquent {
//...
protected $guarded = array(); // Check mass-assignment
}
在这种情况下,status
表必须包含ticket_id
字段作为构建关系的外键。所以,如果一切顺利,那么你可以使用这样的东西:
// Create a new Ticket
$ticket = Ticket::create(array(...));
// Create a new Status
$status = Status::create(array('description' => 'New'));
// Save the relationship
$ticket->status()->save($status);
在这种情况下,我假设您的两个表/模型都将primary key
设置为id
字段。