Laravel Query Builder inherit where of the other var - laravel-5.1

I am with Laravel 5.1, I have this:
$q = Model::where('tipo','<>','');
then I do:
$res1 = $q->where('value','>',1)->get();
$res2 = $q->where('value','>',2)->get();
Then $res2 have inherit the where of $res1 too?
what can be the problem??

You should check Laravel Query Scope
Query Scope will allow you to easily re-use query. Add the query scope function inside your model. Simply prefix a model method with scope:
In Model:
public function scopeFirstCondition($query)
{
return $query->where('value','>',1);
}
public function scopeSecondCondition($query)
{
return $query->where('value','>',2);
}
Then you can fetch the values likewise:
$res1 = Model::firstCondition()->get();
$res2 = Model::secondCondition()->get();
If required you could also combine them:
$result = Model::firstCondition()->secondCondition()->get();
Docs: Laravel Query Scope
Hope this is Helpful.

Related

ASP.NET MVC 5 API, Changing a class in GET function

I'm working on a dotnet mvc5 application. Here's a function from my api of customer controller
public IHttpActionResult GetCustomers()
{
var customerDtos = _context.Customers.ToList().Select(Mapper.Map<Customer, CustomerDto>);
return Ok(customerDtos);
}
I need to add "TYPEAHEAD" plugin to my application. The video series/instructor I'm following says to make the function code change to
public IHttpActionResult GetCustomers(string query = null)
{
var customersQuery = _context.Customers
.Include(c => c.MembershipType);
if (!String.IsNullOrWhiteSpace(query))
customersQuery = customersQuery.Where(c => c.Name.Contains(query));
var customerDtos = customersQuery
.ToList()
.Select(Mapper.Map<Customer, CustomerDto>);
return Ok(customerDtos);
}
in order to make "TypeAhead" plug in work on my view.
The only problem is previously while creating customers I didn't feel the need to add "MembershipType" class to my customer. So how do I use the new code without MembershipType. Is there any other attribute I can replace it with? Name, ID etc.
.Include(c => c.MembershipType);
essentially means that you also want to include the 'child' collection of MembershipType
See here for more information on Loading Related Entities
For your case, you can simply omit this.
public IHttpActionResult GetCustomers(string query = null)
{
var customersQuery = _context.Customers;
if (!String.IsNullOrWhiteSpace(query))
customersQuery = customersQuery.Where(c => c.Name.Contains(query));
var customerDtos = customersQuery
.ToList()
.Select(Mapper.Map<Customer, CustomerDto>);
return Ok(customerDtos);
}
You don't need to replace it with anything.
customersQuery is then an IQueryable<Customer> which the rest of this code can append Where clause to.
It is not executed against the database until the ToList call.

laravel updateOrCreate() with dynamic table

I'm working with project where tables are created all the time depending on user adding new properties, so for my model i have below
class Hotel extends Model
{
public function __construct($hotel)
{
$this->table = $hotel;
}
protected $fillable = ['date', 'sold', 'sold_diff', 'rev', 'rev_diff', 'row', 'date_col', 'sold_col', 'rev_col'];
}
and i can use the table in controller by doing
$hotel_table = new Hotel($table);
but i like to use Model::updateOrCreate() when I'm adding or updating rows in table, and I'm not sure how to do that.
This is the signature for the updateOrCreate function
"static Model updateOrCreate( array $attributes, array $values = array())"
For you to update or create, you can pass the condition that must be met to update the table to the first argument and the values to be updated to the second.
for example.
$primaryKey = isset($request->input('id')) ? $request->input('id') : null;
$myModel = Model::updateOrCreate(['id' => $primaryKey], $request->all());
so with this if id is in the request object the table will be updated but if not a new record will be created.
In Laravel 5.2 you can use simply like this
class Hotel extends Model
{
protect $table = 'hotels'
protected $fillable = ['date', 'sold', 'sold_diff', 'rev', 'rev_diff', 'row', 'date_col', 'sold_col', 'rev_col'];
// protected $guarded = []; you can use this instead of `$fillable` this is for all columns fillable
}
now in your controller you can use
Model::update();
Model::create();

EF Code First to create multiple databases dynamically

Is it possible to generate different databases according to a specific parameter?
My final goal is john.domain.com => create john db, paul.domain.com => create paul db
How could I achieve this using EF6 code first, MVC5? Could model first do it?
Yes you can change the connection string at runtime, something like.
Need to add reference to System.Data.
public static class ConnectionStringExtension
{
public static void ChangeDatabaseTo(this DbContext db, string newDatabaseName)
{
var conStr = db.Database.Connection.ConnectionString;
var pattern = "Initial Catalog *= *([^;]*) *";
var newConStr = Regex.Replace(conStr, pattern, m =>
{
return m.Groups.Count == 2
? string.Format("Initial Catalog={0}", newDatabaseName)
: m.ToString();
});
db.Database.Connection.ConnectionString = newConStr;
}
}
Usage.
using (var db = new AppContext())
{
// Uses it just before any other execution.
db.ChangeDatabaseTo("MyNewDatabase");
}

How to properly send action parameter along with query in BreezeJs

Currently I am calling all data queries as showed on BreezeJs docs / examples:
getEntityList = function (predicate) {
var query = new entityModel.EntityQuery().from("EntityList");
if (predicate)
query = query.where(predicate);
return manager.executeQuery(query);
}
But I want to pass additional parameter to controller action before any queryable result is returned:
[AcceptVerbs("GET")]
public IQueryable<Entity> EntityList(string actionParam) {
//here goes logic that depends on actionParam
//and returns IQueryable<Entity>
}
As we know from documentation:
Breeze converts the query into an OData query string such as this one:
?$filter=IsArchived%20eq%20false&$orderby=CreatedAt
This is where the problem starts. How should I build query to pass param to controller action?
getEntityList = function (predicate, actionParam) {
var query = new entityModel.EntityQuery().from("EntityList");
if (predicate)
query = query.where(predicate);
if(actionParam)
// ???
return manager.executeQuery(query);
}
I already tried setting route to:
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{actionParam}",
defaults: new { query = RouteParameter.Optional }
);
and sending actionParam by applying it in a from section,
var query = new entityModel.EntityQuery()
.from("EntityList/" + encodeURIComponent(actionParam));
but encoding fails on some special chars and bad request is being thrown.
How can I properly send actionParam in such scenario? Please help.
As of v 0.76.1, you can use the EntityQuery.withParameters method to pass additional parameters to any service method. So you can now construct a query like the following that both passes parameters and uses breeze's IQueryable support.
EntityQuery.from("EmployeesFilteredByCountryAndBirthdate")
.withParameters({ BirthDate: "1/1/1960", Country: "USA" })
.where("LastName", "startsWith", "S")
.orderBy("BirthDate");
where your controller method would look something like this:
[HttpGet]
public IQueryable<Employee> EmployeesFilteredByCountryAndBirthdate(DateTime birthDate, string country) {
return ContextProvider.Context.Employees.Where(emp => emp.BirthDate >= birthDate && emp.Country == country);
}
The API docs have more information.
UPDATE: AS OF BREEZE v.0.76.1 THIS IS NO LONGER THE CORRECT ANSWER. BREEZE NOW SUPPORTS PARAMETERS ON QUERIES. SEE THE "withParameters" QUERY CLAUSE.
Support for parameterized queries was added to Breeze thanks in part to this question on SO. Thank you.
This answer used to describe a workaround which is no longer needed. I have revised my answer, eliminating my description of that workaround.

zend framework 2 tutorial AbstractTableGateway

I'm very new to Zend Framework and php.
I went through the Zend Framework 2 tutorial and tried to use AbstractTableGateway for querying multiple tables.
But got the following message on the web page:
The table name of the provided select object must match that of the table
Here is part of my code:
class PublicationTable extends AbstractTableGateway
{
protected $table = 'publication';
public function fetchAll()
{
$sql = new Sql($this->adapter);
$select = $sql->select();
$select->from(array('p' => 'publication'))
->join('author','publication_fk=p.publication_pk');
$resultSet = $this->selectWith($select);
return $resultSet;
}
...
}
I'm aware that the variable "protected $table" is a String.
So how can one resolve this?
Thanks for the help!
EC
The from() method takes a table name, not a list of columns. Use columns() to specify the columns that you want. I've never tried from a TableGateway though as if you are doing joins, then TableGateway isn't the best pattern to follow.
If you use the DbAdapater directly, then something like this should work:
use Zend\Db\Sql\Select,
Zend\Db\ResultSet\ResultSet;
$select = new Select;
$select->from('publication')
->join('author', 'publication.publication_pk = author.publication_fk',
array('columnnamefromauthortable1', 'columnnamefromauthortable2'));
$statement = $adapter->createStatement();
$select->prepareStatement($adapter, $statement);
$resultSet = new ResultSet();
$resultSet->initialize($statement->execute());

Resources