Fluent
Swift animation made easy
How can I select a random row using Eloquent or Fluent in Laravel framework.
I know by using SQL you can do order by RAND(). And I would prefer to do this without doing a count on the number of records prior to the initial query.
Any ideas?
Source: (StackOverflow)
I am quite new to Laravel and Fluent queries.
I have a query to select all the rows from the hire table and display them in a random order.
DB::table('hire_bikes')->order_by(\DB::raw('RAND()'))->get();
I now want to be able to do is put
concat(SUBSTRING_INDEX(description, " ",25),"...") AS description
into the SELECT part of the query, so that i can select * from the table and a shortened description.
I know this is possible by running a raw query, but i was hoping to be able to do this using Fluent or at least partial Fluent (like above).
Any help or ideas?
Thanks
Adam.
Source: (StackOverflow)
$cardQueryList = [];
foreach($cards as $cardName => $quantity) {
$cardQueryList[] = [
'username' => $user->username,
'card_uid' => $card->uid,
'have_quantity' => $quantity
];
}
Collection::insert($cardQueryList);
The above code creates new rows even if the row exists. How can I make it so if the row exists, it updates. And if it doesn't it creates the row? An Eloquent or Fluent answer would be optimal but I'm open to raw if there's no other way.
I would like to do a mass update/insert with a single query. Not a for loop of queries for every record. Ideally I'd like to hit the database once for obvious reasons.
Also I've already checked the following link:
Insert a new record if not exist and update if exist, laravel eloquent
The above works for a single record update/insert. Which if I ran with a for loop would be very slow. I'm looking for an answer that allows a mass insert/update in a single query.
Note: I'm using, both 'username' and 'card_uid' as my key. So basically when I find a row with said username and card_uid, I'd like to update the corresponding row. Otherwise create a new row.
Source: (StackOverflow)
In using Fluent NHibernate, I can't seem to find a good explanation of when you use the cascading option on the References side vs. the HasMany side.
What's the difference (if any) in mapping the following...
References(...).Cascade.All();
vs
HasMany(...).Cascade.All();
My question stems from a problem when saving a parent (root) entity. Once it's saved, I want to insure that all child objects are also persisted.
Source: (StackOverflow)
I've recently been exposed to the fluent interface in nUnit and I love it; however, I am using msTest.
Does anyone know if there is a fluent interface that is either testing framework agnostic or for msTest?
Source: (StackOverflow)
how do we do this mapping but fluently?
<class name="Person" table="People">
<id name="Id">
<generator class="identity"/>
</id>
<property name="Name" />
<join table="Addresses">
<key column="PersonId"/>
<property name="Line1"/>
<property name="Line2"/>
<property name="City"/>
<property name="Country"/>
<property name="ZipCode"/>
</join>
</class>
I know i can use 'References' but i don't need all the columns from the related table. i just need one property.
Source: (StackOverflow)
Say I have a class with some properties and some methods for manipulating those properties:
public class PersonModel
{
public string Name { get; set; }
public string PrimaryPhoneNumber { get; set; }
public void LoadAccountInfo(AccountInfo accountInfo)
{
this.Name = accountInfo.Name;
}
public void LoadPhoneInfo(PhoneInfo phoneInfo)
{
this.PrimaryPhoneNumber = phoneInfo.PhoneNumber;
}
}
Typical usage would be:
var model = new PersonModel();
model.LoadAccountInfo(accountInfo);
model.LoadPhoneInfo(phoneInfo);
I think it would be cool to make the methods chainable:
public PersonModel LoadAccountInfo(AccountInfo accountInfo)
{
this.Name = accountInfo.Name;
return this;
}
public PersonModel LoadPhoneInfo(PhoneInfo phoneInfo)
{
this.PrimaryPhoneNumber = phoneInfo.PhoneNumber;
return this;
}
Then usage would be:
var model = new PersonModel()
.LoadAccountInfo(accountInfo)
.LoadPhoneInfo(phoneInfo);
But I am not returning a modified "clone" of the passed-in PersonModel object in each of these chainable methods. They are just modifying the original object and returning it (for convenience). To me, this creates an ambiguity because someone calling these methods may assume that they are immutable (i.e. they leave the original object intact but return a modified object).
Does that violate any sort of best practice regarding fluent/chainable interfaces?
Source: (StackOverflow)
I have a number of enums in my application
which are used as property type in some classes.
What is the best way to store these values in database, as String or Int?
FYI, I will also be mapping these attribute types using fluent Nhibernate.
Sample code:
public enum ReportOutputFormat
{
DOCX,
PDF,
HTML
}
public enum ReportOutputMethod
{
Save,
Email,
SaveAndEmail
}
public class ReportRequest
{
public Int32 TemplateId
{
get { return templateId; }
set { templateId = value; }
}
public ReportOutputFormat OutputFormat
{
get { return outputFormat; }
set { outputFormat = value; }
}
public ReportOutputMethod OutputMethod
{
get { return outputMethod; }
set { outputMethod = value; }
}
}
Source: (StackOverflow)
"Fluent interfaces" is a fairly hot topic these days. C# 3.0 has some nice features (particularly extension methods) that help you make them.
FYI, a fluent API means that each method call returns something useful, often the same object you called the method on, so you can keep chaining things. Martin Fowler discusses it with a Java example here. The concept kooks something like this:
var myListOfPeople = new List<Person>();
var person = new Person();
person.SetFirstName("Douglas").SetLastName("Adams").SetAge(42).AddToList(myListOfPeople);
I have seen some incredibly useful fluent interfaces in C# (one example is the fluent approach for validating parameters found in an earlier StackOverflow question I had asked. It blew me away. It was able to give highly readable syntax for expressing parameter validation rules, and also, if there were no exceptions, it was able to avoid instantiating any objects! So for the "normal case", there was very little overhead. This one tidbit taught me a huge amount in a short time. I want to find more things like that).
So, I'd like to learn more by looking at and discussing some excellent examples. So, what are some excellent fluent interfaces you've made or seen in C#, and what made them so valuable?
Thanks.
Source: (StackOverflow)
I am using Fluent NHibernate and having some issues getting a many to many relationship setup with one of my classes. It's probably a stupid mistake but I've been stuck for a little bit trying to get it working. Anyways, I have a couple classes that have Many-Many relationships.
public class Person
{
public Person()
{
GroupsOwned = new List<Groups>();
}
public virtual IList<Groups> GroupsOwned { get; set; }
}
public class Groups
{
public Groups()
{
Admins= new List<Person>();
}
public virtual IList<Person> Admins{ get; set; }
}
With the mapping looking like this
Person: ...
HasManyToMany<Groups>(x => x.GroupsOwned)
.WithTableName("GroupAdministrators")
.WithParentKeyColumn("PersonID")
.WithChildKeyColumn("GroupID")
.Cascade.SaveUpdate();
Groups: ...
HasManyToMany<Person>(x => x.Admins)
.WithTableName("GroupAdministrators")
.WithParentKeyColumn("GroupID")
.WithChildKeyColumn("PersonID")
.Cascade.SaveUpdate();
When I run my integration test, basically I'm creating a new person and group. Adding the Group to the Person.GroupsOwned. If I get the Person Object back from the repository, the GroupsOwned is equal to the initial group, however, when I get the group back if I check count on Group.Admins, the count is 0. The Join table has the GroupID and the PersonID saved in it.
Thanks for any advice you may have.
Source: (StackOverflow)
Here is my query using fluent query builder.
$query = DB::table('category_issue')
->select('issues.*')
->where('category_id', '=', 1)
->join('issues', 'category_issue.issue_id', '=', 'issues.id')
->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
->group_by('issues.id')
->order_by(DB::raw('COUNT(issue_subscriptions.issue_id)'), 'desc')
->get();
As you can see, I am ordering by a count from the joined table. This is working fine. However, I want this count returned with my selections.
Here is the my raw sequel query that works fine.
Select issues.*, COUNT(issue_subscriptions.issue_id) AS followers
FROM category_issue JOIN Issues ON category_issue.issue_id = issues.id
LEFT JOIN issue_subscriptions ON issues.id = issue_subscriptions.issue_id
WHERE category_issue.category_id = 1
GROUP BY issues.id
ORDER BY followers DESC
How would I go about this select using Laravel's fluent query builder? I am aware I can use a raw sql query but I would like to avoid that if possible. Any help would be appreciated, thanks in advance!
Source: (StackOverflow)
I was wondering if there is any library that can be used to represent SQL queries as objects in Java.
In the code I have plenty of static variables of type java.lang.String that are hand written SQL queries. I would be looking for library having a nice fluent API that allows me to represent the queries as objects rather than strings.
Example:
Query q = select("DATE", "QUOTE")
.from("STOCKMARKET")
.where(eq("CORP", "?"))
.orderBy("DATE", DESC);
Source: (StackOverflow)
This is a human interface question about combining the step builder pattern with the enhanced or wizard builder patterns into a creational DSL. It uses a fluent like interface, although it uses method chaining not cascading. That is, the methods return differing types.
I’m confronting a monster class that has two constructors that take a mix of ints, Strings, and an array of Strings. Each constructor is 10 parameters long. It also has about 40 optional setters; a few of which conflict with each other if used together. Its construction code looks something like this:
Person person = Person("Homer","Jay", "Simpson","Homie", null, "black", "brown",
new Date(1), 3, "Homer Thompson", "Pie Man", "Max Power", "El Homo",
"Thad Supersperm", "Bald Mommy", "Rock Strongo", "Lance Uppercut", "Mr. Plow");
person.setClothing("Pants!!");
person.setFavoriteBeer("Duff");
person.setJobTitle("Safety Inspector");
This eventually fails because it turns out having set both favorite beer and job title is incompatible. Sigh.
Redesigning the monster class is not an option. It’s widely used. It works. I just don’t want watch it being constructed directly any more. I want to write something clean that will feed it. Something that will follow its rules without making developers memorize them.
Contrary to the wonderful builder patterns I’ve been studying this thing doesn’t come in flavors or categories. It demands some fields all the time and other fields when needed and some only depending on what has been set before. The constructors are not telescoping. They provide two alternate ways to get the class into the same state. They are long and ugly. What they want fed to them varies independently.
A fluent builder would definitely make the long constructors easier to look at. However, the massive number of optional setters clutters the required ones. And there is a requirement that a cascading fluent builder doesn’t satisfy: compile time enforcement.
Constructors force the developer to explicitly add required fields, even if nulling them. This is lost when using a cascading fluent builder. The same way it's lost with setters. I want a way to keep the developer from building until each required field has been added.
Unlike many builder patterns, what I’m after isn’t immutability. I’m leaving the class as I found it. I want to know the constructed object is in a good state just by looking at the code that builds it. Without having to refer to documentation. This means it needs to take the programmer thru conditionally required steps.
Person person = PersonBuilder
// -- These have good default values, may be skipped, and don't conflict -- //
.doOptional()
.addClothing("Pants!!") //Could also call addTattoo() and 36 others
// -- All fields that always must be set. @NotNull might be handy. -- //
.doRequired() //Forced to call the following in order
.addFirstName("Homer")
.addMiddleName("Jay")
.addLastName("Simpson")
.addNickName("Homie")
.addMaidenName(null) //Forced to explicitly set null, a good thing
.addEyeColor("black")
.addHairColor("brown")
.addDateOfBirth(new Date(1))
.addAliases(
"Homer Thompson",
"Pie Man",
"Max Power",
"El Homo",
"Thad Supersperm",
"Bald Mommy",
"Rock Strongo",
"Lance Uppercut",
"Mr. Plow")
// -- Controls alternatives for setters and the choice of constructors -- //
.doAlternatives() //Either x or y. a, b, or c. etc.
.addBeersToday(3) //Now can't call addHowDrunk("Hammered");
.addFavoriteBeer("Duff")//Now can’t call addJobTitle("Safety Inspector");
.doBuild(); //Not available until now
Person may be built after addBeersToday() since at that point all constructor info is known but is not returned until doBuild().
public Person(String firstName, String middleName, String lastName,
String nickName, String maidenName, String eyeColor,
String hairColor, Date dateOfBirth, int beersToday,
String[] aliases);
public Person(String firstName, String middleName, String lastName,
String nickName, String maidenName, String eyeColor,
String hairColor, Date dateOfBirth, String howDrunk,
String[] aliases);
These parameters set fields that must never be left with default values. beersToday and howDrunk set the same field different ways. favoriteBeer and jobTitle are different fields but cause conflicts with how the class is used so only one should be set. They are handled with setters not constructors.
The doBuild method returns a person object. It's the only one that does and person is the only type it will return. When it does person is fully initialized.
At each step of the interface the type returned is not always the same. Changing the type is how the developer is guided though the steps. It only offers valid methods. The doBuild() method isn’t available until all needed steps have been completed.
The do/add prefixes are a kludge to make writing easier because the changing return type
mismatches with the assignment and makes intelisense recommendations become alphabetical
in eclipse. I've confirmed intellij doesn't have this problem. Thanks NimChimpsky.
This question is about the interface, so I'll accept answers that don't provide an implementation. But if you know of one, please share.
If you suggest an alternative pattern please show it's interface being used. Use all the inputs from the example.
If you suggest using the interface presented here, or some slight variation, please defend it from criticisms like this.
What I really want to know is if most people would prefer to use this interface to build or some other. This is human interface question. Does this violate PoLA? Don't worry about how hard it would be to implement.
However, if you are curious about implementations:
A failed attempt (didn't have enough states or understand valid vs not defaulted)
A step builder implementation (not flexible enough for multiple constructors or alternatives)
An enhanced builder (Still liner but has flexible states)
Wizard builder (Deals with forking but not remembering the path to pick a constructor)
Requirement:
- The monster (person) class is already closed to modification and extension; no touchy
Goals:
- Hide the long constructors since the monster class has 10 required parameters
- Determine which constructor to call based on alternatives used
- Disallow conflicting setters
- Enforce rules at compile time
Intent:
- Clearly signal when default values are not acceptable
Source: (StackOverflow)
Given the following scenario, I want map the type hierarchy to the database schema using Fluent NHibernate.
I am using NHibernate 2.0
Type Hierarchy
public abstract class Item
{
public virtual int ItemId { get; set; }
public virtual string ItemType { get; set; }
public virtual string FieldA { get; set; }
}
public abstract class SubItem : Item
{
public virtual string FieldB { get; set; }
}
public class ConcreteItemX : SubItem
{
public virtual string FieldC { get; set; }
}
public class ConcreteItemY : Item
{
public virtual string FieldD { get; set; }
}
See image
The Item
and SubItem
classes are abstract.
Database Schema
+----------+ +---------------+ +---------------+
| Item | | ConcreteItemX | | ConcreteItemY |
+==========+ +===============+ +===============+
| ItemId | | ItemId | | ItemId |
| ItemType | | FieldC | | FieldD |
| FieldA | +---------------+ +---------------+
| FieldB |
+----------+
See image
The ItemType
field determines the concrete type.
Each record in the ConcreteItemX
table has a single corresponding record in the Item
table; likewise for the ConcreteItemY
table.
FieldB
is always null if the item type is ConcreteItemY
.
The Mapping (so far)
public class ItemMap : ClassMap<Item>
{
public ItemMap()
{
WithTable("Item");
Id(x => x.ItemId, "ItemId");
Map(x => x.FieldA, "FieldA");
JoinedSubClass<ConcreteItemX>("ItemId", MapConcreteItemX);
JoinedSubClass<ConcreteItemY>("ItemId", MapConcreteItemY);
}
private static void MapConcreteItemX(JoinedSubClassPart<ConcreteItemX> part)
{
part.WithTableName("ConcreteItemX");
part.Map(x => x.FieldC, "FieldC");
}
private static void MapConcreteItemY(JoinedSubClassPart<ConcreteItemY> part)
{
part.WithTableName("ConcreteItemX");
part.Map(x => x.FieldD, "FieldD");
}
}
FieldB
is not mapped.
The Question
How do I map the FieldB
property of the SubItem
class using Fluent NHibernate?
Is there any way I can leverage DiscriminateSubClassesOnColumn
using the ItemType
field?
Addendum
I am able to achieve the desired result using an hbm.xml file:
<class name="Item" table="Item">
<id name="ItemId" type="Int32" column="ItemId">
<generator class="native"/>
</id>
<discriminator column="ItemType" type="string"/>
<property name="FieldA" column="FieldA"/>
<subclass name="ConcreteItemX" discriminator-value="ConcreteItemX">
<!-- Note the FieldB mapping here -->
<property name="FieldB" column="FieldB"/>
<join table="ConcreteItemX">
<key column="ItemId"/>
<property name="FieldC" column="FieldC"/>
</join>
</subclass>
<subclass name="ConcreteItemY" discriminator-value="ConcreteItemY">
<join table="ConcreteItemY">
<key column="ItemId"/>
<property name="FieldD" column="FieldD"/>
</join>
</subclass>
</class>
How do I accomplish the above mapping using Fluent NHibernate?
Is it possible to mix table-per-class-hierarchy with table-per-subclass using Fluent NHibernate?
Source: (StackOverflow)
Does anyone have an example how to set up and what entities to cache in fluent nhibernate. Both using fluent mapping and auto mapping?
And the same for entity relationships, both one-to-many and many-to-many?
Source: (StackOverflow)