function delete_ScormByIdPlataforma($id_platform)
{
$query = $this->db->query("delete from scormvars where scoinstanceid in
(select scoinstanceid from dispatch where id_licencia in
(select id_licencia from licencias where id_plataforma = $id_platform))");
// return true;
}
This is my function in my model, the query is ok, but I don't know how to execute the query.
You load the model class, then call the function:
$this->load->model('my_class');
$this->my_class->delete_ScormByIdPlataforma($id_platform);
Replacing my_class with the name of the class.
Related
So I have a Student model with this function:
public function latestStatus()
{
return $this->hasOne(StatusStudent::class)->latest();
}
then I just do a query with this latestStatus()
$query = Student::findOrFail(1);
$query = $query->whereHas('latestStatus', function($query) use ($statusuri) {
$query->where('status_id', 1);
});
dd($query->toSql());
and the toSql() function returns:
"select * from `students` where exists (select * from `status_student` where `students`.`id` = `status_student`.`student_id` and `status_id` = ?)
as if latest() is ignored.
Why doesn't latest() add anything to the query?
Thanks.
Edit:
I tried adding selectRaw for example:
public function latestStatus()
{
return $this->hasOne(StatusStudent::class)->selectRaw('MAX(status_student.id)');
}
and still nothing appears in my query.
If you dig deeper to the whereHas() relationship. It calls the has() method then if you look for the has() method you will see the getRelationWithoutConstraints() method, means that it will call the relationship but it will remove all the constraints attach to it and will only call the base query instance :
public function latestStatus()
{
return $this->hasOne(StatusStudent::class)->latest(); // the latest() will be removed in the query if you call the `latestStatus` using the `whereHas() or has()`
}
so if you use the whereHas() like the way you use it :
"select * from `students` where exists (select * from `status_student` where `students`.`id` = `status_student`.`student_id` and `status_id` = ?)
it will return the query with out the latest().
Instead of doing it like that you can do it like :
Student Model
public function status() : HasOne
{
return $this->hasOne(StatusStudent::class);
}
Controller
$student = Student::findOrFail(1);
$student->whereHas('status', function($query) {
$query->where('status_id', 1)
->latest();
})
But since the relationship is define as one-to-one :
$student = Student::findOrFail(1);
$student->load('status');
or
$student = Student::findOrFail(1)->status()->get();
Maybe you want to get the latest of all the status.
StudentStatus::query()->latest()->get();
As stated in a comment by #matticustard,
findOrFail() returns a model, not a query builder.
Instead of findOrFail(1) use where('id', 1)
Here is my query which works as well:
SELECT sum(r.rating) as rank,b.* FROM books as b
LEFT JOIN ranks as r ON b.id = r.book_id
WHERE 1
GROUP BY (b.id)
ORDER BY rank DESC
Now I want to do the same in Laravel. Here is what I've tried:
// Book model
class Book extends Model
{
public function ranks()
{
return $this->hasMany(Rank::class)->sum("rating");
}
}
// Controller
$obj = new Book;
$get = $obj->ranks()->orderBy('rating', 'desc')->get();
It throws this error:
Call to a member function groupBy() on integer
Any idea how can I fix this problem?
public function ranks() {
return $this->hasMany(Rank::class)
->select('book_id', \DB::raw('sum(`rating`) as `rank`'))
->groupBy('book_id');
}
$books = Book::with('ranks')->get();
$sortedBooks = $books->sortByDesc(function($book) {
return $book->ranks->sum('rank');
});
In my Yii2 project I have post and post_views tables, and a Post model.
There are 2 fields in post_views:
post_id
views_counter
I'm using PostSearch and PostsQuery (ActiveQuery) for my queries.
My Task is: I need to get all my posts with custom field views where I get views_counter from post_views.
I'm not using hasMany in model because there is no model for post_views table in the project and I'd prefer not to create it if possible. Also, I need to sort my posts by views field. I'm stuck on this:
public function topPosts(){
$junction_table = '{{%post_views}}';
return $this->innerJoin($junction_table, Post::tableName().'.id='.$junction_table.'.post_id');
}
The main problem is that I don't know how to join and return data properly.
I need this query:
SELECT p.*, pv.views_count FROM posts p INNER JOIN post_views pv ON p.id = pv.post_id ORDER BY pv.views_count DESC;
First, you need to update your Post model with viewCount field:
class Post extends \yii\db\ActiveRecord
{
private $viewCount;
public static function tableName()
{
return "posts";
}
public function setViewCount($viewCount)
{
$this->viewCount = $viewCount;
}
public function getViewCount()
{
return $this->viewCount;
}
}
Then you need to include viewCount field in select list like this:
$post = new Post();
$query = $post->find()
->alias('p')
->select(['p.*', 'pv.views_count viewCount'])
->innerJoin("post_views pv", "p.Id = pv.id")
->limit(100)
->orderBy(["pv.views_count" => SORT_DESC]);
//Get SQL query string
echo $query->createCommand()->getSql();
//Execute query
$result = $query->all();
I am trying to implement following join query
SELECT * from users as u
LEFT JOIN `table1` as ou
ON ou.user_id = u.id
LEFT JOIN table2 as o
ON o.id = ou.orid
LEFT JOIN table3 as p
ON o.pra_id = p.id;
with my laravel model so i create a function named alldata() in my user model with following code
public function alldata()
{
return $this
->leftjoin('table1','users.id','=','table1.user_id')
->leftjoin('table2','table1.orid','=','table2.id')
->leftjoin('table3','table2.pra_id','=','table3.id');
}
now when i try to access the data by $gd = User::find(1)->getall() it returns results with all the table
but when i try to acces $gd = User::all()->alldata() it gaves error mathod not found
how can i resolve this
thanks
The User::find(1) function returns an single instance of the object (or NULL if not found).
The User::all() function returns a Collection of all User objects.
You need to create a query then get() the results as follows...
public static function alldata()
{
return self::query()
->leftjoin('table1','users.id','=','table1.user_id')
->leftjoin('table2','table1.orid','=','table2.id')
->leftjoin('table3','table2.pra_id','=','table3.id')
->get();
}
Assuming your your alldata() method is in the User class you can call the function with the following code:
User::alldata();
Laravel has a excellent database relationship system which is most defiantly worth looking at. It would make queries like the one above much simpler...
https://laravel.com/docs/5.1/eloquent-relationships
I want to select users from a database with Doctrine and Symfony. Depending on whether I have a supplied list of user IDs I want to only select users with these IDs. If the list is empty, then all users should be selected.
Here is the code I have created so far:
class UserRepository extends EntityRepository {
public function selectUsers (array $userIds) {
$dql = "
SELECT
u
FROM
MyBundle:User
WHERE
u.id IN (:users)"; // OR (:users) does not contain any values
$query = $this
->getEntityManager()
->createQuery($dql)
->setParameter("users", $userIds);
return $query->getResult();
}
}
How can I check whether the array is empty? So far, I have tried IS EMPTY, = (), = [], SIZE(:users) = 0, COUNT(:users) = 0 but all of them give me errors. What is the correct syntax here?
You can dynamically build DQL query
public function selectUsers(array $userIds)
{
$dql = "SELECT u FROM MyBundle:User";
$params = array();
if ($users) {
$dql .= " WHERE u.id IN (:users)";
$params["users"] = $userIds;
}
return $this->getEntityManager()->createQuery($dql)->execute($params);
}
You are building two different queries - select all, select specific users. I think you cannot build such SQL query. Maybe DQL has some shortcut how you can do it, but I would prefer SQL-ish syntax.
The only solution I have come up with so far is to calculate the count in PHP and pass it in as an additional parameter.
class UserRepository extends EntityRepository {
public function selectUsers (array $userIds) {
$dql = "
SELECT
u
FROM
MyBundle:User
WHERE
u.id IN (:users) OR :userCount = 0";
$query = $this
->getEntityManager()
->createQuery($dql)
->setParameter("users", $userIds)
->setParameter("userCount", count($userIds));
return $query->getResult();
}
}
However, I have a hard time believing that this is impossible to do directly in DQL.