问题描述
我有一个元框可以在书的帖子类型中插入 ISBN。这是我的代码:
// the two shadow properties mapped to the computed columns
modelBuilder.Entity<Friendship>()
.Property<Guid>("UserId1")
.HasComputedColumnsql("case when SenderId < ReceiverId then SenderId else ReceiverId end");
modelBuilder.Entity<Friendship>()
.Property<Guid>("UserId2")
.HasComputedColumnsql("case when SenderId < ReceiverId then ReceiverId else SenderId end");
// the unique index using them
modelBuilder.Entity<Friendship>()
.HasIndex("UserId1","UserId2")
.IsUnique();
现在我想验证 ISBN 是否唯一,如果它不是唯一的,我们就不应该存储书帖类型和 book_info。我该怎么做?
解决方法
您可以通过在插入之前添加预查询来检查 isbn 代码是否存在。未经测试,但应该可以工作:
function book_isbn_meta_box_save($post_id){
$isbn = $_POST['isbn'];
global $wpdb;
$table_name = $wpdb->prefix . "books_info";
$existing = $wpdb->get_var("SELECT post_id from $table_name WHERE isbn = $isbn;")
if (!$existing) {
$wpdb->insert( $table_name,array( 'post_id' => $post_id,'isbn' => $isbn ) );
}
}