I use the Zend 2 Framework to build my web application. I implemented my database table models by this tutorial: http://framework.zend.com/manual/2.1/en/user-guide/database-and-models.html
I have a many-to-many relationship between two models in my database. To get data from them I googled and found this link: http://mattmccormick.ca/2010/04/24/how-to-easily-create-models-and-table-relationships-in-zend-framework/
The problem is that all the table models extends from Zend_Db_Table_Abstract in the example. I don't know how to get data from the models.
I have a table containing votings, every voting has a unique hash id. Every voting also has tags. Therefore I defined a table tags with all the tags available and a voting_tag_map where all many-to-many relationships are mapped.
What I have tried so far is the following, that's code from my VotingTable class:
public function getTagsByVoting($votingHash){
$select = $this->tableGateway->getSql()->select();
$select->from(array('v' => 'voting'))
->join('voting_tag_map', 'v.voting_id=voting_tag_map.voting_id')
->join('tags', 'voting_tag_map.tag_id=tags.tag_id');
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}
It says then:
Since this object was created with a table and/or schema in the constructor, it is read only.
Thats because of the from() method. If I delete the from() method, it says:
Statement could not be executed
Can anyone help me please?
Since this object was created with a table and/or schema in the constructor, it is read only.
This error is because you are trying to set the table name in the from clause, but it's already been set in the contructor of the TableGateway, and you can't change it once set.
If you really need to do this then you can extens AbstractTableGateway yourself then you won't have to add a string tablename to the contructor, but you don't really need to use an alias on your main table...
The SQL error you get when you comment out the from() method will be due to your referencing the votes table as it's alias 'v' in your join, when you are not using the alias v, try changing it to 'voting.XXX' from 'v.XXX'
Related
We can add page relationship in two different ways using named relationships and pages data type which is kind of advanced content modelling in Kentico..
if we go through named relationships then we can give a meaningful relationship between to content node by providing description. So, we get a relationship name called “is related to”(example). When we use this in practice, then we get [page A] {is related to} [Page B].
if we go through pages data type then we assign some content on the form tab, records are created in the “CMS_Relationship” table as ad-hoc via the “RelationshipIsAdHoc” column and there is no relationship name for this as such. It is marked as Ad-hoc. and Relationship name is also added page type name underscore some randon guid example abc.product_3d628a37-7637-4a21-b0b4-e1dd1a00a3bc
My question is when we try to use page data type and we need to add relationship through api code, then how can we add because in kentico api to add page relationship through api code RelationShipNameID is mandatory field. We don't have this RelationShipNameID as we are not going through named relationship.
Found out the way
Need to retrieve ad-hoc relatioshipnameinfo object, e.g. like this:
string codeName = GetAdHocRelationshipNameCodeName("fillclassnamehere", field);
var relationshipNameInfo = GetRelationshipNameInfo(codeName);
and then use is with API:
RelationshipInfoProvider.AddRelationship(leftSiteId, rightSiteId, relationshipNameInfo.RelationshipNameId)
I have a database with table Photos and table Categories. Each photo is related to one category by categoryId field.
What happens when I delete one category from Categories table? Will the photos with that category be updated with a null value in the categoryID? Or how will entity-framework react to this change?
Another question can I then reset with a mass-change the values of those categories in the photos table? And how can I do that?
hi if you have created relationship between table(using foreign key) then only the deletion of parent table will affect deletion of child table. if you just created table separately and managing relationship with your code then it will not affect the child table. if you are creating using model first approach in entity framework with specifying relation then relationship will be automatically created in backend.
their are four options available in sql on deletion of parent entity
1)No Action
2)Cascade
3)SET NULL
4)SET Default
to know how it will affect check this article
https://www.mssqltips.com/sqlservertip/2365/sql-server-foreign-key-update-and-delete-rules/
That would depend completely on how the ORM that is used defines the database model.
Assuming you use Entity Framework then you can define exactly how EF should react to that situation. In the DbContext you should find a OnModelCreating method in wich you can specify per table what restrictions you want on the table. There you can also define the behaviour of the OnDelete of a foreign key.
If you are not using EF but have your own or a different ORM then again, it depends on how that ORM is configured.
Simple check if you dont know about the used ORM is this: Does the field in the database have a foreign key and how is that configured? Also, is the field categoryID (as defined in the database) nullable? if so, then it apparently doesnt need the relation and shouldnt result in related deletes.
I've got three tables (there's actually several more, but I only need the three for this problem). Applications, Appattrs and Appcats. In CakePHP parlance (as best as I can since I'm still learning the framenwork) Applications hasMany Appattrs and Appattrs belongsTo Applications. Easy.
The problem comes when I want to associate Appattrs and Appcat - the association is predicated on a field value and a corresponding foreign key in Appattrs. For instance:
If appattrs.type = 'appcatid' then appattrs.value would point to a record in the Appcat table.
The appattrs table holds static data appattrs.type='dateadded' and value='201201011300' as well as foreign key references. I'd rather not get into a discussion as to why data is stored this way, I just want to figure out how to create associations that will let me pull an application record, the associated attr records and then an attr record with its associated row from the appropriate table. Dynamically.
It seems to me that I should be able to create a model based on a query and then associate that model - I just can't seem to figure out how to do that.
--
If I need to post schema for the three tables, I can. I can also post my current model code, but honestly, right now it's just association variables so I don't think it'll get anyone anywhere.
Thow I do not understand the logic behind this design, I thing what you are looking for
is Creating and Destroying associations on the fly.
On this section of CakePHP Docs, it describes how you can associate models from within the corresponding controller.
So, for example, when you want to save specific data to Appattr model you can do some data checking and create your association using bind() method.
A very abstract approach to the above would be something like this
public function yourmethod() {
...
if ($this->request->data['Appattr']['type'] == 'sometype') {
$this->Appattr->bindModel(
array(/*Your association*/ => array(/* Your attributes...*/)
);
/* Rest of the logic follows */
}
}
This way you get your job done, but it's very possible to end up having very complicated
data in your database and thus having very complicated code.
I hope this helps
Is there an easy way to manage many-to-many relationships in the new seeds feature of L4?
One way would be to make a seed for the pivot table, but I would be a lot of work.
Any thoughts on a good workflow for this sort of thing?
In the latest version of Laravel 4 you define the order that all the seeder scripts are run in the "run" method of the DatabaseSeeder class.
public function run()
{
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
$this->call('PrimaryTableOneSeeder');
$this->command->info('The first primary table has been seeded!');
$this->call('PrimaryTableTwoSeeder');
$this->command->info('The second primary table has been seeded!');
$this->call('PivotTableSeeder');
$this->command->info('The pivot table has been seeded!');
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}
You'll notice that I disable the foreign key constraints before and after running all my seeding. This may be bad practice but it's the only way I can use the truncate function to re-set the id count for each table. If you follow the guide on inserting related models this practice may be unnecessary.
class PrimaryTableOneSeeder extends Seeder {
public function run()
{
DB::table('primaryone')->truncate();
Primaryone::create(array(
'field' => 'value',
'created_at' => new DateTime,
'updated_at' => new DateTime
));
}
To use mass assignment as I'm doing in my example and as the latest version of the documentation does, you'll need to specify either some guarded or fillable columns for the model. To do this simply add property to your model like this:
class Primaryone extends Eloquent {
protected $guarded = array('id');
Laravel seed files are regular PHP scripts (except they need to return an array). You can query the database in seed files (using Eloquent, Fluent builder or even PDO).
One way to tackle the many-to-many problem is to deliberately name your seed files so that the pivot table is populated last... For example, you could prepend a numeric value to the file name (i.e. 1_authors.php, 2_books.php, 3_authors_books.php etc.). Artisan sorts the filenames alphabetically before executing them.
I have posted a small tutorial on Laravel 4 database seeding - this should get you going. Additionally, you may consult the official doc on seeding.
Seeding is for simple information, test data and static information. I wouldn't recommend using it to handle relationships. Personally, I only use it for 2 or 3 record per table, to help test my application.
When developing your application, think about working on the data entry (admin) area first then the front end. That way you can easily add test data.
I'm having a little bit of trouble saving data to a database. Basically, I have a main table that has associations to other tables (Example Below).
Tbl_Listing
ID
UserID - Associated to ID in User Table
CategoryID - Associated to ID in Category Table
LevelID - Associated to ID in Level Table.
Name
Address
Normally, it's easy for me to add data to the DB (using Entity Framework). However, I'm not sure how to add data to the fields with associations. The numerous ID fields just need to hold an int value that corresponds with the ID in the associated table.
For example; when I try to access the column in the following manner I get a "Object reference not set to an instance of an object." error.
Listing NewListing = new Listing();
NewListing.Tbl_User.ID = 1;
NewListing.Tbl_Category.ID = 2;
...
DBEntities.AddToListingSet(NewListing);
DBEntities.SaveChanges();
I am using NewListing.Tbl_User.ID instead of NewListing.UserID because the UserID field is not available through intellisense.
If I try and create an object for each related field I get a "The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects." error.
With this method, I am trying to add the object without the .ID shown above - example NewListing.User = UserObject.
I know this should be simple as I just want to reference the ID from the associated table in the main Listing's table. Any help would be greatly appreciated.
Thanks in advance,
-S
In general, with Entity Framework you don't use the ID:s of foreign keys, instead you use references. Instead of setting the ID, you set the property of the associated table.
In your case, it would be something like this:
Listing newListing = new Listing();
newListing.Tbl_User = DBEntities.Users.Single(u=>u.ID == 1);
newListing.Tbl_Category = DBEntities.Categories.Single(c=>c.ID == 2);
...
DBEntities.AddToListingSet(newListing);
DBEntities.SaveChanges();
In Entity Framework 4 (coming with .NET 4.0) you'll be able to use a simpler syntax more like what you expected.
You can have a look at this article on msdn where you can read more about this!