If i have 2 primary key?

QuestionsIf i have 2 primary key?
Daniel Febres asked 10 years ago

I have a table with 2 primary key, how can i set 2 primary key?
$col = array();
$col["title"] = "FK_Franquicia";
$col["name"] = "FK_Franquicia";
$col["width"] = "0";
$col["editable"] = true;
$cols[] = $col;

$col = array();
$col["title"] = "FK_Servicio";
$col["name"] = "FK_Servicio";
$col["width"] = "0";
$col["editable"] = true;
$cols[] = $col;

1 Answers
Abu Ghufran answered 10 years ago

For composite keys – there are two possible approaches:

1) Creating a new AUTO_INCREMENT column directly in the database, so that each row has a unique id, then using this column for primary key. You can hide the column using hidden => true.

2) In your SELECT statement (select_command), you may try to select a first column as special concat value that is based on composite keys. This will handle the listings. For insert/update/delete, you will need to use custom events on_update/on_insert/on_delete to parse the new concat field and perform desired operation. Refer demos/editing/custom-events.php for help.

// example code 1

$g->select_command = "SELECT concat(pk1,'-',pk2) as pk, col2, col3 FROM table";

$e["on_insert"] = array("add_client", null, true);
$g->set_events($e);

function add_client($data)
{
$pk = $data["params"]["pk"];
list(pk1, pk2) = explode("-",$pk);

$data["params"]["pk1"] = $pk1; // setting $data will make sure it will be there in INSERT SQL
$data["params"]["pk2"] = $pk2;
}

// example code 2

// Step1: Select concatenated PK with combined composite key
$g->select_command = "SELECT concat(Year_No,'-',Order_No,'-',LocationID,'-',TranscationId) as pk, Year_No, Order_No, LocationID, TranscationId, Startdate, ExpiredDate FROM mylocations ";

// Step2: Connect on_update event hander
$e["on_update"] = array("update_data", null, false);
$g->set_events($e);

// Step3: In handler, split the PK with your separator, and execute custom UPDATE query
function update_data($data)
{
list($Year_No,$Order_No,$LocationID,$TranscationId) = explode("-",$data["pk"]);

$s = array();
foreach($data["params"] as $k=>$v)
{
$s[] = "$k = '$v'";
}
$s = implode(",",$s);

$w = "Year_No=$Year_No and Order_No=$Order_No and LocationID=$LocationID and TranscationId=$TranscationId";

mysql_query("UPDATE mylocations set $s WHERE $w");
}

[^ Top](#top)

Your Answer

13 + 2 =

Login with your Social Id:

OR, enter

Attach code here and paste link in question.
Attach screenshot here and paste link in question.



How useful was this discussion?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate it.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?