How to get specific column from Model in zf2 - zend-framework2

I have function in model, in which i retrieve data from database based on id,it display me all data of table. However I want to display only password I means specific column's data, How can I do this?
here is my function.
public function getProfile($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row1 = $rowset->current();
print_r($row1);
exit;
}
This code display me:
Admin\Model\Profile Object ( [id] => 9 [name] => Ayaz1 khan [email] => ayaz1#yahoo.com [password] => 51e232a1579ba7074ba4e2d09c956dcb [inputFilter:protected] => ) .

Guess your problem's answer just lies there, simply add a
$select->where(array('id' => $id)); on the Select object : zf2 tablegateway select columns by column name
use Zend\Db\Sql\Select as Select;
$select = new Select();
$select->from('tableName');
$select->columns(array('password'));
$select->where(array('id' => $id));
$resultSet = $this->tableGateway->selectWith($select);

Related

how to apply inner join in entityframework LINQ method syntax?

How to apply this query in entity framework method syntax
select company_id, country_id from companies, departments where companies.company_id == departments.company_id and department.departmentId = 10;
So far, I have:
var company = context.companies
.Where(com => com.Departments
.Contains(context.departments
.Where(dep => dep.department_id==_user.Department)
.FirstOrDefault()
)
)
.Select(com => new { com.company_id, com.Country })
.FirstOrDefault();
Using method based syntax, this could be as simple as;
var company = context.Companies
.Where(x => x.Departments
.Any(x => x.department_id == _user.Department)
)
.Select(x => new { x.company_id, x.Country });
This assumes your tables are set up with foreign keys giving each Company a list of Department objects. It very much depends on your data structure.

Yii2 hasMany with many conditions in join statement

I need to define more conditions in the JOIN statement.
How can I make this in Yii2 with a hasMany relation?:
... LEFT JOIN orders ON (customer.id = order.customer_id AND orders.position = 1) ...
I have a DataProvider for GridView. It look like this:
...
public function search($params)
{
$query = Customer::find()
->joinWith('orders');
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
return $dataProvider;
}
...
Model:
...
public function getFirstOrder()
{
$query = $this->hasMany(Orders::className(), ['customer_id' => 'id']);
return $query;
}
...
Is it even possible?
public function search($params){
$activeDataProvider = new ActiveDataProvider([
"query" => Customer::find()
->joinWith('orders')
]);
// Valdate the search $params.
// Build your query depending on search params. I am assuming we get key => value pair in params
foreach($params as $key => $value){
$activeDataProvider->query->andWhere("`$key` = '$value'");
}
return $activeDataProvider;
}
I hope that helps you :)
You can also preview the generated sql using:
$command = $activeDataProvider->query->createCommand();
print_r ($command->sql);

Pass a result of multiple grouping to View

Db.Deliveries.Where(d => d.CrewId != null).GroupBy(d => new {d.Crew, d.Date}).OrderBy(d => d.Key).ToList()
How to pass the result of this code to View? Code is valid. What type must have View?
var Deliveries = Db.Deliveries.Where(d => d.CrewId != null).GroupBy(d => new {d.Crew, d.Date}).OrderBy(d => d.Key).ToList(); //It`s Ok.
List<IGrouping<{Crew:Crew, Date:DateTime}, Delivery>> Deliveries = Db.Deliveries.Where(d => d.CrewId != null).GroupBy(d => new {d.Crew, d.Date}).OrderBy(d => d.Key).ToList(); //It`s wrong.
List<IGrouping<{Crew, DateTime}, Delivery>> //This type is wrong too.
Or is exists any solution of this problem, without using anonymious types?
Sorry for my bad English, Thanks for any help!
Because you use an anonymous type in your GroupBy the result the type exists only virtually.
Either use
#model dynamic
or define a type for your result
public class GroupedDelivery{
public Crew Crew {get;set;}
public DateTime Date {get;set;}
public List<Delivery> Deliveries {get;set;}
}
Map the type in a Select after the GroupBy.
List<GroupedDelivery> Deliveries = Db.Deliveries.Where(d => d.CrewId != null)
.GroupBy(d => new {d.Crew, d.Date})
.Select(p => new GroupedDelivery{
Crew = p.Key.Crew,
Date = p.Key.Date,
Deliveries = p.Select(x => x).ToList()
})
.OrderBy(d => d.Crew).ThenBy(p => p.Date).ToList();

MVC 4 explicitly load a many to many EF lookup and filter by both keys

I have the following in an MVC4 app. I want to filter the load by both keys, there could be many to many but both the keys together represent a unique row. The goal to to explicitly load these collections only when needed and filter by both sides of the relationship.
I have the following Entity.DBContext, it works but only for the UserId key.
context.UserProfiles.Include(o => o.CoachOfOrginizations).Where(p => p.UserId == UserId).Single()
Also this loads all of them, but of course doesnt filter at all, just showing you so you know that I set up my fluent code properly.
context.Entry(this).Collection(t => t.AdministratorOfOrginizations).Load();
modelBuilder.Entity<UserProfile>()
.HasMany(p => p.CoachOfOrginizations)
.WithMany(t => t.Coaches)
.Map(mc =>
{
mc.ToTable("OrganizationCoaches");
mc.MapLeftKey("UserProfileID");
mc.MapRightKey("OrganizationID");
});
CoachOfOrginizations is the following property on UserProfile.
public ICollection<Organization> CoachOfOrginizations { get; set; }
What i would like is to filter my original .Include above based on Organization.ID (the other key) and the currently used key p.UserId. I've tried the following and it doesn't work, any advice? "this" is the UserProfile object.
context.Entry(this)
.Collection(b => b.CoachOfOrginizations)
.Query()
.Where(p => p.ID == orgID)
.Load();
You can do both filtering in a single query. See conditional includes.
var query = context.UserProfiles
.Where(p => p.UserId == UserId)
.Select(p => new { p, Orgs = p.CoachOfOrginizations.Where(o => o.ID == orgID) });
var profiles = query.AsEnumerable().Select(a => a.p);

ValueInjecter with IQueryable<T>

I need to map IQueryable<User> to IQueryable<SimpleUser> with ValueInjecter.
Is this possible?
I tried:
return userRepo.GetUsers()
.Select(o => new SimpleUser().InjectFrom(o))
.Cast<SimpleUser>();
But this cannot be translated to a stored expression...well, the method InjectFrom.
Can automapper do this?
I want something similar to this:
return from i in userRepo.GetUsers()
select new SimpleUser{
i.UserId,
i.Name
};
but with using some kind of mapper tool.
Convert the collection to objects before doing the select and it should work. Updated using PredicateBuilder to show filtering and paging and Dynamic LINQ for sorting.
var predicate = new PredicateBuilder<User>.True();
if (!string.IsNullOrEmpty( typeFilter ))
{
predicate = predicate.And( u => u.Type == typeFilter );
}
if (!string.IsNullOrEmpty( nameFilter ))
{
predicate = predicate.And( u => u.Name.StartsWith( nameFilter ));
}
// assumes sortColumn matches one of your user properties and
// sortDirection is either "ASC" or "DESC"
string sortOrder = string.Format( "{0} {1}", sortColumn, sortDirection );
return userRepo.GetUsers()
.Where( predicate )
.OrderBy( sortOrder )
.Skip( (page-1) * usersPerPage )
.Take( usersPerPage )
.ToList() // force the query and make these objects
.Select(o => new SimpleUser().InjectFrom(o))
.Cast<SimpleUser>();

Resources