我与事物有联系。连接上下。我想保留状态的历史记录并了解连接的当前状态。我有一个连接模型。 Connection有许多ConnectionStatus。首先,我想在Connection上创建一个属性,该属性是当前状态,它也限制ConnectionStatus中的列。到目前为止我已经这样做了:
public function insertImages($pic_files,$pic_numbers,$sg_id){
$check_insert_number = 0 ;
$upload_path = '../uploads/sg/';
$upload_path_fake = 'uploads/sg/';
$server_ip = gethostbyname(gethostname());
$upload_url = 'http://'.$server_ip.'/keepwords/'.$upload_path_fake;
foreach($pic_files as $key => $value) {
$fileinfo = pathinfo($value['name']);
$extension = $fileinfo['extension'];
$image_name_temp = pathinfo($value['name'], PATHINFO_FILENAME);
$image_name = time()."_".$image_name_temp;
$file_url = $upload_url . $image_name . '.' . $extension;
$file_path = $upload_path . $image_name . '.'. $extension;
try{
move_uploaded_file($value['tmp_name'],$file_path);
$source = imagecreatefrompng($file_path);
$rotate = imagerotate($source, 90, 0);
imagepng($rotate,$file_path);
$stmt=$this->conn->prepare("INSERT INTO sg_image(url,sg_id) values (?,?)");
$stmt->bind_param("si",$file_url,$sg_id);
$result=$stmt->execute();
if($result){
$check_insert_number++;
} else {
}
}catch(Exception $e){
die($e->getMessage());
}
}
if($check_insert_number==$pic_numbers) {
return 1 ;
}else {
return 0 ;
}
}
我不知道如何通过current_status完成排序。以下是一些有助于解释的理想用法
class Connection < ApplicationRecord
has_many :connection_statuses, -> { order(created_at: :desc) }
def current_status
status = connection_statuses.first
status.nil? ? 'unknown' : status.description
end
end
这是一个我不理解的一般概念。感谢您的帮助!
答案 0 :(得分:0)
自current_status
以来,您无法执行您所描述的内容,因为您已定义它是模型方法,而不是表属性,因此不能在ActiveRecord关系中使用它。但是你可以将has_many关系别名化为仅限第一条记录的限制。
你可以这样做......
class Connection < ApplicationRecord
has_many :connection_statuses, -> { order(created_at: :desc) }
has_many :current_connections, -> { order(created_at: :desc}.limit(1) }, class_name: 'ConnectionStatus'
让你做...
disconnected_items = Connection.join(:current_connections).where("connection_statuses.description = 'disconnected'")