ORM, CRUD and inserting records with many to many relations using FuelPHP - fuelphp

Being completely new to FuelPHP I have a few questions...
I started creating a simple blog application using Oils scaffolding functionality. After that I've set up all relations between my tables following the ORM docs (tables are called 'posts', 'categories' and 'categories_posts' ). Everthing works perfectly and as espected so far, e.g. selecting data with relations (posts and their associated categories).
But now I'm stuck with creating new posts using the form generated by Oil. I've modified it and added a checkbox for every category stored in the DB. Submitting the form will insert a record into the 'posts' table but not into the 'categories_posts' table.
Is this a matter of naming the checkboxes correctly? Or do I need to write a model for the 'categories_posts' table? What am I missing?

You don't need to create a model for the categories_posts table.
On the action_create() method in Controller_Posts, the database insertion code should be something like:
try
{
$post = Model_Post::forge();
$post->title = Input::post('title');
$post->text = Input::post('text');
/* the next line will create the relation between the two tables */
$post->categories[] = Model_Category::find(Input::post('category_id'));
if ($post and $post->save())
{
/* the post has been saved */
}
else
{
/* something went wrong */
}
}
catch (\Orm\ValidationFailed $e)
{
/* validation error */
}
You can check the examples for establishing and breaking has-many relations on the documentation.

Related

In Objection.js, what's the benefit of setting up relationMappings?

I'm kind of confused about what relationMappings do inside a Objection.js Model class.
I thought once we setup the relationMapping inside a Model, we will get related data in every query. But, it turns out that I still only the Model properties itself.
Is there anything else I should use to get related data in query?
Relation mappings gives model semantics how relations can be fetched when they are needed. It would be really bad for performance to always query all related rows in addition to main table's row. When you create relation mappings to model, you will not need to write joins manually every time you need to query relations. Also they enable many other objection features, which requires information how row relations goes in DB.
To use relation mappings in query Objection.js requires that within every query you must tell which relations you want to fetch with the main row with .withGraphFetched or .withGraphJoined methods https://vincit.github.io/objection.js/guide/query-examples.html#eager-loading
for example:
class Person extends Model {
static get tableName() {
return 'persons';
}
static get relationMappings() {
return {
pets: {
relation: Model.HasManyRelation,
modelClass: Animal,
join: {
from: 'persons.id',
to: 'animals.ownerId'
}
}
};
}
}
const people = await Person.query().withGraphFetched('pets');
// Each person has the `pets` property populated with Animal objects related
// through the `pets` relation.
console.log(people[0].pets[0].name);
console.log(people[0].pets[0] instanceof Animal); // --> true
Mappings are also used when you insert nested object data with .insertGraph so that related objects are inserted to related tables and foreign key references etc. are automatically filled according to relation mapping declarations.
There are many other places where those are used, but I hope this gives a rough idea why they exist.

How to use table valued function in entity framework code first approach?

i am working on a project using Entity Framework and now i got a situation where i need to use table valued function which returns table with 2 columns, hence i searched a lot and i came to know that we use table valued functions in Database first approach while i needed it in Code first.
here is the situation
i have a table with two columns
Table1
Id int PK
priority int
i want to use this table in my query in EF.
Is their any way i can use Table Valued function?
We can do this by using the c# code generated by the CLR for Database first approach
you can refer this url for the full description
http://blogs.msdn.com/b/adonet/archive/2011/06/30/walkthrough-table-valued-functions-june-ctp.aspx
i had used this code and it worked fine for me
[EdmFunction("NorthwindEntities", "GetDetailsForOrder")]
public IQueryable<Order_Detail> GetDetailsForOrder(Nullable<global::System.Int32> oid)
{
ObjectParameter oidParameter;
if (oid.HasValue)
{
oidParameter = new ObjectParameter("Oid", oid);
}
else
{
oidParameter = new ObjectParameter("Oid", typeof(global::System.Int32));
}
return base.CreateQuery<Order_Detail>("[NorthwindEntities].[GetDetailsForOrder](#Oid)", oidParameter);
}
I created a custom model convention which allows using store functions in CodeFirst in EF6.1. The convention is available on NuGet http://www.nuget.org/packages/EntityFramework.CodeFirstStoreFunctions. Here is the link to the blogpost containing all the details: http://blog.3d-logic.com/2014/04/09/support-for-store-functions-tvfs-and-stored-procs-in-entity-framework-6-1/

Laravel eloquent has_many_and_belongs_to sync() without writing to database

In short, does Laravel's eloquent have something like it's sync() functionality that doesn't save the relationships to the database right away?
I have two models
Place (id, name, address);
and
Feature (id, name);
These two models has a has_many_and_belongs_to relationship with each other, using the pivot table
feature_place(place_id, feature_id). This works as expected. Now I'm trying trying to build a form for creating a new Place. The form contains a checkbox for each existant Feature. For error handling I want to be able to create a Place object when the form is submitted. I'd like to be able to create my HABTM relationship, so I can easily rebuild and fill the form if submission fails (validation error or similar). sync() would usually handle the relationships, but since the submission has failed I don't want to insert the Place in the database yet.
Is there an easy way, like sync(), to create the relationship between my Place and it's Features that I can use to repopulate my form on rebuild, without having to write to the database before form submission succeeds?
It sounds like you need to flash the input to the session and then load the old values when the form is rendered.
// Somewhere in your post route
if ( $oh_noes_teh_validator_failed )
{
Input::flash();
Redirect::to_route( 'my-edit-form' );
}
// Somewhere in your edit route or view
$title = Input::old( 'title', $title );

Attaching an related entity to new entity, without retrieving from database

I've just started working with Web API this week, and I'm struggling with something which I think should be quite simple, but haven't been able to find the answer for yet. Perhaps I'm searching using the wrong terms.
One of the calls to the API passes through a GUID. I need to create a new entity (using Entity Framework) and set one of the relations to this newly passed in GUID. This GUID is the ID of a different entity in the database.
I'm struggling to attach the entity via the relation without fetching the whole entity too.
For example,
public void DoWork(IList<Guid> userGuids)
{
Order order = new Order() // This is an entity
{
CreateDate = DateTime.Now,
CreatedBy = "Me",
Items = (from i in this.Model.Items
where i.Id == userGuid
select i).ToList<Item>();
}
Model.Orders.Add(order);
Model.SaveAll();
}
In the above, I have to do a database call to attach the Item entities to the Order. Is there not a way around this? Seems very redundant to retrieve the whole entity objects when I only require their IDs (which I already have anyway!)!
One solution is stub entities as asked here: Create new EF object with foreign key reference without loading whole rereference object
Link to the source blog referenced: http://blogs.msdn.com/b/alexj/archive/2009/06/19/tip-26-how-to-avoid-database-queries-using-stub-entities.aspx
Snip from the blog - to be applied to your situation:
Category category = new Category { ID = 5};
ctx.AttachTo(“Categories”,category);
Product product = new Product {
Name = “Bovril”,
Category = category
};
ctx.AddToProducts(product);
ctx.SaveChanges();
This way (in the example) the Product is saved without ever loading the Category object.

zend db table model and query multiple tables

Just like in codeigniter model class, can we have multiple methods calling different tables in zend framework model that extends zend_db_table_abstract ?
protected $_name = table_name
when defining table name like that, Is there a way to query multiple table having no affect of that protected property ? I am mainly concern about this because I want to have model for homepage which will deal with frontend website and fetch data from different table so that i don't have to touch backend db-table models.
You can also access the DB adapter member in the table and query it directly, specifying a table name of your choice.
For instance, for a select, you can do something like the following:
$select = $this->getAdapter()->select();
$select->from('tableName', $fields);
// ...
$results = $this->getAdapter()->fetchAll($select);
Hope that helps,
Try protected $_name = array(1=>'table1', 2=>'table2', /*etc...*/);
And add a foreach() to your code when the query is made, like this:
foreach ($_name as $table)
{
// execute your query
}
It should work, I used this in my CMS for the AdminZone...